Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android UI 優化(二):用 include 標簽復用布局

編輯:關於 Android 程式設計

問題:重復的布局怎麼辦

假設下面這塊布局在很多界面都用到了,我該怎麼辦?每個頁面都寫一遍的話,代碼太冗余,並且後續維護難度成倍增加——改一處就得記着同步改十幾處,漏一處就是 bug。

傳統做法有兩種:一是複製粘貼,二是寫個方法在代碼裡動態生成。前者難維護,後者讓視圖邏輯散落在 Java 代碼裡,設計稿一改就得動代碼。更好的答案是 <include> 標簽。

include 標簽的作用

把公共部分抽成獨立布局文件,然後在需要的地方 include 進來:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <include layout="@layout/activity_clude_item" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="這是中間的東西" />
</LinearLayout>

效果如下:

上邊這個布局用的就是 include 標簽。代碼顯然更加整潔,並且增加了布局的復用性,同時因為去掉重復的 XML 解析,也降低了 app 的內存佔用與啟動耗時。

include 標簽的用法

最基本的寫法只有一個屬性:

<include layout="@layout/activity_clude_item" />

其中我們使用 layout="@layout/activity_clude_item" 指定要復用的布局文件。

除此之外還有幾個屬性可以覆寫被引入布局根節點的屬性:

<include
    android:id="@+id/header"
    layout="@layout/header_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="visible" />

實踐中的注意事項

  1. 覆寫 layout 參數需要同時寫全 layout_width 和 layout_height。這是 Android 布局加載器(LayoutInflater)的既定行為:如果你想覆寫任何 layout_* 屬性,就必須把宽高兩個都寫上,否則會拋 IllegalArgumentException,提示你必須同時指定 both width and height。
  2. 可覆寫的屬性是有限的白名單。目前支持覆寫的只有 android:id 以及 android:layout_* 這組參數。想改被引入布局根節點的 background、padding 是不行的,此時應該在被引入的布局文件內部修改,或者用 <merge> 搭配代碼操作。
  3. android:id 的覆寫會蓋掉原 id。如果同一個布局被 include 兩次且都覆寫了 id,那麼兩處的 id 相同,findViewById 會有歧義。需要區分時,可以在 include 標簽上指定不同 id,再通過它去查找子 View。
  4. include 與 merge 的選擇。<include> 引入的是一個完整的布局,會多一層根節點;<merge> 則是把子元素直接合併到父容器中,不產生額外層級。如果你在意層級深度,可以考慮在被引入的布局裡用 <merge> 作為根節點,但要注意 merge 不能獨立使用,必須配合 include 或 ViewStub.inflate()。
  5. 過度抽取反而有害。如果某塊布局只在兩三處使用,而且各處差異較大,那麼為它單獨建文件並到處覆寫屬性,反而讓代碼更難讀。復用的判斷標準是「結構穩定 + 使用頻次高」,例如標題欄、底部操作欄、空數據提示、加載中提示這類。

配合 <style> 抽取屬性、<color> 與 <dimen> 資源抽取具體數值,整個布局體系的復用性會有質的提升——這三者搭配使用,才是 Android 布局層的完整優化方案。

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