2012-03-01 59 views
0

看起來像是一種錯誤的方法,但我仍然會問。在Android中作爲'this'加載佈局

任務是,你有一個佈局xml描述一個複合小部件(如Button + TextView)。你想,使其可重複使用的,所以你創建像MyTextViewButtonWidget一類 - 它會暴露其按鈕文本的存取,它也將文本視圖做同樣的:

public class MyTextViewButtonWidget extends LinearLayout { 
    ... 
    void setButtonText(String text) { ... } 
    String getButtonText() { ... } 
    void setTextViewText(String text) { ... } 
    String getTextViewText() { ... } 
    ... 
} 

佈局定義是這樣的:

<LinearLayout ..........> 
    ....button and text label here... 
</LinearLayout> 

的問題是 - 你將如何加載此佈局使得它的根LinearLayout將是MyTextViewButtonWidgetLinearLayout一部分?

試圖定義這樣MyTextViewButtonWidget的構造函數:

{ 
    inflate(getContext(), R.layout.reusable_widget_layout, this); 
} 

但這加載reusable_widget_layout爲孩子MyTextViewButtonWidget(這不是我所需要的)。

一般來說,問題是:

  • 您需要創建一個複合構件
  • 你想能夠定義與XML標記佈局
  • 你想它加載根的子物件在XML定義它的子控件(INSTEAD OF:加載XML從整個層次爲您的可重用部件的一個孩子)

回答

2

替換:

<LinearLayout ..........> 
    ....button and text label here... 
</LinearLayout> 

有:

<merge ..........> 
    ....button and text label here... 
</merge> 
+0

救了我的天!謝謝 :-) – agibalov 2012-03-01 12:48:27