2012-03-01 56 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