android - 覆盖android :id attribute with <include> doesn't work

标签 android layout include

根据文档,如果我将 id 设置为 <include>标记在 XML 资源文件中,那么它应该覆盖包含布局的 Root View 的 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>

merge_layout.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");
}

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

最佳答案

您设法解决了这个问题,因为您包含的布局恰好是 ViewGroup 类型,它可以是 xml 根元素。如果不是这种情况 - 即您只有一个 TextView,您将需要使用合并标签,不幸的是问题会出现。事实上,include 不能覆盖已合并为根的布局 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.

关于android - 覆盖android :id attribute with <include> doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16897232/

相关文章:

ruby-on-rails - 更改设备默认布局

PHP - 将 <head></head> 数据作为包含加载是否愚蠢

android - 如何避免 Android 上的 Oauth 2.0 回调

android - 如何保持一个activity之前的状态

android - iTextPdf : Android : Proguard issues with fonts , res/font/sfui_semibold.ttf 找不到文件或资源

java - 使用带有 PrimeFaces 的 JSF 单击菜单后 CSS 丢失

android - 如何在 android 的另一个 Activity 中使用任何其他布局的组件(setContentView() 中定义的除外)

c++ - 如何#include 作为函数参数的字符串?c++

c++ - 编译器忽略我的包含 -I 新库版本

android - 如何从 Android 中的 EditText 中提取 HTML 样式的文本?