2013-06-03 21 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>標籤解決了問題。