天天看點

提高顯示布局檔案的性能 2 - 使用include标簽重用Layout Re-using Layouts with <include/>

盡管android提供了很多種小的元件可以重用,我們還需要自定義一些稍微複雜一點的小元件進行重用。我們可以使用<include/> and <merge/> 标簽來對目前的layout嵌入一些其他的layout.

在建立一個稍微複雜一點的layout時,重用layout是個很給力的方法。比如我們需要一個yes/no的控制欄,包含文字提示的progress bar。這意味着我們可以在很多地方重用那些自定義的layout.

如果你已經知道哪些元件是會重用的,我們可以建立一個xml并且定義這個layout。

例如:下面定義了一個需要在每個activity都需要顯示的titlebar.xml

<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>  

下面示例了一個包含了titlebar控件的布局:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"  

    android:orientation="vertical"   

    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裡面的屬性,例如:

<include android:id=”@+id/news_title”  

         android:layout_width=”match_parent”  

         android:layout_height=”match_parent”  

         layout=”@layout/title”/>  

某些時候,自定義可重用的布局包含了過多的層級标簽,比如我們需要在linearlayout裡面嵌入一個重用的元件,而恰恰這個自定義的可重用的元件根節點也是linearlayout,這樣就多了一層沒有用的嵌套,無疑這樣隻會拖慢程式速度。而這個時候如果我們使用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"/>  

        android:text="@string/delete"/>  

</merge>  

這樣的話,使用<include>包含上面的布局的時候,系統會自動忽略merge層級,而把兩個button直接放置與include平級。

繼續閱讀