提高顯示布局文件的性能 2 - 使用include標簽重用Layout
Re-using Layouts with <include/>
盡管Android提供了很多種小的組件可以重用,我們還需要自定義一些稍微複雜一點的小組件進行重用。我們可以使用<include/> and <merge/> 標簽來對當前的layout嵌入一些其他的layout.
在創建一個稍微複雜一點的layout時,重用layout是個很給力的方法。比如我們需要一個YES/NO的控製欄,包含文字提示的Progress bar。這意味著我們可以在很多地方重用那些自定義的layout.
例如:下麵定義了一個需要在每個Activity都需要顯示的titlebar.xml
- <FrameLayout xmlns:android="https://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>
Use the <include> Tag [使用<include>標簽]
下麵示例了一個包含了titlebar控件的布局:- <LinearLayout xmlns:android="https://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裏麵的屬性,例如:
- <include android:id=”@+id/news_title”
- android:layout_width=”match_parent”
- android:layout_height=”match_parent”
- layout=”@layout/title”/>
Use the <merge> Tag [使用<merge>標簽]
某些時候,自定義可重用的布局包含了過多的層級標簽,比如我們需要在LinearLayout裏麵嵌入一個重用的組件,而恰恰這個自定義的可重用的組件根節點也是LinearLayout,這樣就多了一層沒有用的嵌套,無疑這樣隻會拖慢程序速度。而這個時候如果我們使用merge根標簽就可以避免那樣的問題。例如:
- <merge xmlns:android="https://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>
最後更新:2017-04-04 07:03:06