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

用 merge + include 優化 Android 版面:減少嵌套、提升顯示效能

編輯:關於 Android 程式設計

Android 的版面若嵌套太多層,會拖累效能。想解決這個問題,可以在 include 引入時搭配 merge 作為根節點,藉此削減多餘的嵌套層級。本文記錄這個技巧的用法與它的侷限。

基本原理

每個版面檔都需要一個根節點,但嵌套過深會造成效能問題。當你透過 include 引入子版面時,若把子版面的根節點設為 merge,就能把多餘的容器拿掉,讓顯示更有效率。

先用 merge 作為根節點,裡面放幾個 TextView:

 <merge xmlns:android="https://schemas.android.com/apk/res/android" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="張三" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="李四" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="王五" /> </merge> 

再在主版面中透過 include 把它引入,這時 merge 內的元素會直接「嵌」進父容器,而不多一層包裹:

 <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="horizontal" tools:context="com.example.viewstub.MainActivity" > <include layout="@layout/top"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="顯示/隱藏" /> <ViewStub android:id="@+id/vs" android:layout_margin="50dp" android:layout_width="match_parent" android:layout_height="match_parent" android:inflatedId="@+id/inflated_id" android:layout="@layout/view_stub_layout" /> </LinearLayout> 

它的侷限

merge 最大的限制在於:merge 內元素的排列方式會「跟隨主版面」。以上面的例子來說,主版面是水平排列的 LinearLayout,那麼 merge 內的元素被引入後也會水平排列;若你希望它們垂直排列,merge 本身辦不到。理解這個特性後,就能在適當的場合善用 merge 來優化版面效能了。

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