[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/>的位置裏去

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章