Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 include 標籤整合 Android 版面:讓複雜 UI 保持結構清晰

編輯:Android 開發實例

Android 的版面檔讓我們能很方便地安排元件位置與屬性,程式端也能直接取得元件並賦予行為。但如果遇到複雜的介面設計,把所有內容都塞進同一個 XML,檔案會迅速膨脹成難以維護的巨物。

為此 Android 提供了 <include> 標籤——顧名思義就是「包含」,能把多個版面檔組裝在一起。用法非常簡單,以下用三個檔案示範。

父版面 layoutP

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <include android:id="@+id/cell1" layout="@layout/includeA" />
    <include android:id="@+id/cell2"
        android:layout_width="fill_parent"
        layout="@layout/includeB" />
</LinearLayout>

子版面 layoutA

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:text="雨楓技術教程網 www.fengfly.com!"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</TextView>

子版面 layoutB

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:text="FENGFLY.COM"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</TextView>

經過 layoutP 的整合,layoutA 與 layoutB 就成了它的子元素。整個版面的結構變得清楚、可讀性提高,介面上的功能模塊也能被明確切分開來。

實務提醒

<include> 有個容易踩的規則:只能覆寫 layout_* 這類版面參數,其他屬性(如 android:id 以外的樣式)不會生效。因此若需要客製被包含區塊的樣式,正確做法是把屬性寫在子版面自己的根節點上。另外被 include 的版面根節點必須同時具備 layout_width 與 layout_height,否則會引發例外。與 include 相關的還有 <merge>(消除多餘的巢狀層級)與 <ViewStub>(按需延遲載入),三者搭配能明顯改善複雜頁面的效能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved