[Android 效能最佳化系列]布局篇之通過<include>複用布局,android效能最佳化
大家如果喜歡我的部落格,請關注一下我的微博,請點擊這裡(http://weibo.com/kifile),謝謝
轉載請標明出處(http://blog.csdn.net/kifile),再次感謝
原文地址:http://developer.android.com/training/improving-layouts/reusing-layouts.html
在接下來的一段時間裡,我會每天翻譯一部分關於效能提升的Android官方文檔給大家
效能最佳化布局篇:
[Android 效能最佳化系列]布局篇之減少你的介面層級
題外話:
很多時候,我們都會用到類似的布局,既然如此,我們不妨將相同布局整體抽出來,單獨作為一個布局檔案使用,這樣我們就避免了在多個檔案中反覆書寫同樣地代碼,並且當我們需要修改的時候,也只需要修改一個地方就好了。
下面是本次的本文:
################
雖然安卓為我們提供了一系列的控制項來方便我們進行互動,你或許還是需要重複使用到一些特定布局的大型組件。為了更有效複用布局,你應該使用<include/>和<merge/>來讓一個布局出現在另一個布局中,而不是在每一個布局檔案中都重寫他。
在這種情況下,複用布局是格外有用的,他允許你建立一個複雜的可重用布局。比如說,一個 yes/no 按鈕,一個擁有文字的自訂進度條。這也意味著,你應用中的一些元素是通用的。所以你可以單獨為他們建立一個自訂 View,這樣一來你可以更方便的重用布局
建立一個可重用的布局
如果你已經知道哪些布局你希望能夠反覆使用,那麼單獨為他們建立一個新的布局檔案吧。比如說,這裡有一個來自 G-Kenya 代碼實驗室的布局,它定義了一個標題列,而這個標題列會被每一個 activity 所引用
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width=”match_parent” android:layout_height="wrap_content" android:background="@color/titlebar_bg"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gafricalogo" /></FrameLayout>
這個 View 應該同你希望他在每個 Activity 中的顯示效果一致。
使用<include>標籤
當你希望添加一個可重用的組件到另一個布局中時,你可以使用<include/>標籤。比如說,這裡有一段來自 G-Kenya 代碼實驗室的代碼,他想要包含了上面提到的標題列
這裡是他的布局檔案
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width=”match_parent” android:layout_height=”match_parent” android:background="@color/app_bg" android:gravity="center_horizontal"> <include layout="@layout/titlebar"/> <TextView android:layout_width=”match_parent” android:layout_height="wrap_content" android:text="@string/hello" android:padding="10dp" /> ...</LinearLayout>
同樣的,你可以在<include/>標籤內重寫布局檔案的參數,比如說類似於 android:layout_*的屬性,來定義包含的布局的屬性,例如
<include android:id=”@+id/news_title” android:layout_width=”match_parent” android:layout_height=”match_parent” layout=”@layout/title”/>
不管如何,如果你希望使用<include>標籤重寫布局屬性,你必須要重寫 layout_height 和 layout_width 來讓其他屬性生效
使用<merge>標籤
<merge/>標籤在能夠有效協助我們降低你的布局層級。比如說,你的布局是一個垂直的線性布局,並且你希望複用的布局也是一個類似的垂直的線性布局。那麼,使用另外一個線性布局作為重用布局的根項目會導致一個垂直的線性布局中包含另一個垂直的線性布局。這種嵌套的線性布局沒有任何意義,並且會降低你的 ui 效能
為了避免上面的情況發生,你可以在你重用的布局中使用<merge>標籤作為根項目,例如下面這樣
<merge xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/add"/> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/delete"/></merge>
這樣一來,當你使用<include/>標籤進行複用的時候,系統會忽略掉<merge>標籤,然後就將兩個 Button 按鈕放到<include/>的位置裡去