根據文檔,如果我爲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");
}
然後它每次都拋出第二個異常。我錯過了什麼嗎?
這是爲什麼不支持?難道是不是太複雜或甚至不可能在LayoutInflater中實現這一點?也許有人可以在這裏發佈補丁:https://source.android.com/source/submit-patches.html。我不太理解LayoutInflater膨脹視圖的方式遞歸地也沒有時間學習它,但如果有人能這樣做會很棒...... –