1

根据文档,如果我<include>为 XML 资源文件中的标签设置了一个 id,那么它应该覆盖包含布局的根视图的 id。但是,它似乎不起作用。

我创建了一个非常简单的项目来演示它:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/merge_layout" />

</RelativeLayout>

合并布局.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</merge>

现在如果我运行这个:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (findViewById(R.id.button) == null)
        throw new RuntimeException("button is null"); // Never happens
    if (findViewById(R.id.test) == null)
        throw new RuntimeException("test is null");
}

然后它每次都会抛出第二个异常。我错过了什么吗?

4

2 回答 2

3

您设法解决了这个问题,因为您包含的布局恰好是 ViewGroup 类型,它可以是 xml 根元素。如果不是这种情况 - 即您只有一个 TextView ,您将需要使用合并标签,不幸的是问题会出现。事实是,include 不能覆盖已合并为 root 的布局 xml 的 id,如下面的 LayoutInflater 源中所示...它使合并标记不太有用:(

if (TAG_MERGE.equals(childName)) {
// Inflate all children.
rInflate(childParser, parent, childAttrs, false);
} else {
//...
// We try to load the layout params set in the <include /> tag.
//...
// Inflate all children.
rInflate(childParser, view, childAttrs, true);

// Attempt to override the included layout's android:id with the
// one set on the <include /> tag itself.
// While we're at it, let's try to override android:visibility.
于 2013-07-23T21:56:57.300 回答
0

好的,答案很明显,我误解了它的<merge>工作原理。我认为这个标签是强制性的,但事实并非如此。结果是android:id被应用于<merge>标签而不是<LinearLayout>.

删除<merge>标签解决了这个问题。

于 2013-07-07T11:45:47.273 回答