2013-06-03 23 views
1

根据文档,如果我为XML资源文件中的<include>标记设置了一个id,那么它应该覆盖包含的布局根视图的id。但是,它似乎并不奏效。用<include>覆盖android: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"); 
} 

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

回答

3

你设法解决了这个问题,因为你的包含的布局恰好是一个ViewGroup类型,它可以是一个xml根元素。如果不是这种情况 - 即你只有一个TextView,你需要需要来使用合并标签,不幸的是问题会出现。事实是,包括不能覆盖已合并为根,如下LayoutInflater源看到一个布局XML的ID ......这使得合并标签不太有用:(

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. 
+0

这是为什么不支持?难道是不是太复杂或甚至不可能在LayoutInflater中实现这一点?也许有人可以在这里发布补丁:https://source.android.com/source/submit-patches.html。我不太理解LayoutInflater膨胀视图的方式递归地也没有时间学习它,但如果有人能这样做会很棒...... –

0

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

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