Android XML布局的“包含”标签真的有用吗?

我在我的Android布局文件中使用<include>时无法覆盖属性。 当我search错误,我发现拒绝发行2863 :

“包括标签被破坏(压倒一切的布局参数从来没有工作)”

由于罗曼指出这在testing套件和他的例子中是有效的,所以我一定是做错了。

我的项目是这样组织的:

res/layout buttons.xml res/layout-land receipt.xml res/layout-port receipt.xml 

buttons.xml包含这样的东西:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button .../> <Button .../> </LinearLayout> 

纵向和横向receipt.xml文件如下所示:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> ... <!-- Overridden attributes never work. Nor do attributes like the red background, which is specified here. --> <include android:id="@+id/buttons_override" android:background="#ff0000" android:layout_width="fill_parent" layout="@layout/buttons"/> </LinearLayout> 

我错过了什么?

我刚刚发现这个问题。 首先,你只能覆盖layout_ *属性,所以背景不起作用。 这是logging的行为,只是我的一个疏忽。

真正的问题在LayoutInflater.java中find:

 // We try to load the layout params set in the <include /> tag. If // they don't exist, we will rely on the layout params set in the // included XML file. // During a layoutparams generation, a runtime exception is thrown // if either layout_width or layout_height is missing. We catch // this exception and set localParams accordingly: true means we // successfully loaded layout params from the <include /> tag, // false means we need to rely on the included layout params. ViewGroup.LayoutParams params = null; try { params = group.generateLayoutParams(attrs); } catch (RuntimeException e) { params = group.generateLayoutParams(childAttrs); } finally { if (params != null) { view.setLayoutParams(params); } } 

如果<include>标记不包括layout_width和layout_height,那么RuntimeException就会发生,并且被默默处理,甚至没有任何日志语句。

如果要覆盖任何layout_ *属性,解决scheme是在使用<include>标记时始终同时包含layout_width和layout_height。

我的例子应该改为:

 <include android:id="@+id/buttons_override" android:layout_width="fill_parent" android:layout_height="wrap_content" layout="@layout/buttons"/> 

我提交了一个增强请求 ,允许覆盖所有包含的属性:

假设我有两个相同的布局,而不是TextView字段的值。 目前,我要么在运行时修改布局,要么复制XML。

例如,要传递值为“hello”和“world”的两个参数到layout1:

<include layout="@layout/layout1a" params="textView=hello|editText=world" />

layout1a.xml:

<merge><TextView text="@param/textView"><EditText hint="@param/editText"></merge>

另一个实现会破坏封装,并允许include语句覆盖如下的值:

<include layout="@layout/layout1b" overrides="@id/textView.text=hello|@id/editText.hint=world" />

layout1b.xml:

<merge><TextView id="@+id/textView"><EditText hint="@+id/editText"></merge>

我发现在Eclipse中使用GUI构build器时,有时会错过包括android:id标记。 确保(当我注意到)我从生成器添加到TextView中,我在ListView布局中使用的ID。

 <TextView android:text="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> ... 

 <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> ... 

而不是'假''假'我得到:),包括工作正常。