使用 <include layout="@layout/global_header" /> 引入通用標題列,嘗試在主佈局中用 android:layout_below="@global/header" 定位,卻報錯:No resource found that matches the given name。
<!-- 主佈局 -->
<RelativeLayout ...>
<include layout="@layout/global_header" />
<ScrollView
android:layout_below="@global/header" <!-- 報錯處 -->
...>
</ScrollView>
</RelativeLayout>
<!-- global_header.xml -->
<RelativeLayout
android:id="@+global/header" <-- 定義 ID
...>
...
</RelativeLayout>
<include> 標籤預設不會保留被引入佈局根元素的 android:id。被引入的佈局根視圖 ID 會被忽略,導致主佈局找不到 @global/header。
<RelativeLayout ...>
<include
layout="@layout/global_header"
android:id="@+global/header" <-- 關鍵:在這裡重新賦予 ID -->
/>
<ScrollView
android:layout_below="@global/header" <-- 現在能正確找到 -->
...>
</ScrollView>
</RelativeLayout>
<include> 實際上是將引入佈局的內容合併到當前佈局樹中id)預設會被丟棄<include> 標籤上顯式宣告 android:id,該 ID 才會生效於合併後的視圖層級@+id/ 語法表示「若不存在則建立新資源 ID」<include> 也可覆寫 layout_width、layout_height 等佈局參數:
<include
layout="@layout/global_header"
android:id="@+global/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" />
| 錯誤做法 | 正確做法 | 說明 |
|---|---|---|
在被引入佈局根元素設 android:id | 在 <include> 標籤設 android:id | 引入時根元素屬性不保留 |
android:layout_below="@id/global/header" | android:layout_below="@global/header" | 同一佈局檔內引用用 @id/ 或 @+id/ 均可,但跨檔引用需完整包名 |
忘記 + 號 | 首次宣告用 @+id/ | 建立新資源 ID |
使用 <include> 時,必須在 include 標籤上指定 android:id,被引入佈局根元素的 ID 不會生效。這是 Android 佈局合併機制的設計特性,而非 Bug。