Android官方开发文档Training系列课程中文版:布局性能优化之布局复用
原文地址:http://android.xsoftlab.net/training/improving-layouts/reusing-layouts.html
盡管Android提供了種類繁多的常用控件,但是有時你可能希望重用一些比較復雜的布局。如果要重用這些布局,可以使用< include/>標簽與< merge/>標簽,它們可將一個布局嵌入進另一個布局中。
可重用布局這項功能特別強大,它可以使你創建那些復雜的可重用布局。比方說,可以用來創建一個含有yes和no按鈕的容器或者一個含有progressBar及一個文本框的容器。它還意味著程序可以對這些布局進行單獨控制。所以,雖然說你可以通過自定義View的方式來實現更為復雜的UI組件,但是重用布局的方法更簡便一些。
創建一個可重用的布局
如果你已經知道哪一個布局需要重用,那么就創建一個新的xml文件用來定義這個布局。下面就定義了一個ActionBar的布局文件,眾所周知,ActionBar是會在每個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>使用< include/>標簽
在希望添加重用布局的布局內,添加< include/>標簽。下面的例子就是將上面的布局加入到了當前的布局中:
<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>你也可以重寫布局的參數,但只僅限于以android:layout_*開頭的布局參數。就像下面這樣:
<include android:id=”@+id/news_title”android:layout_width=”match_parent”android:layout_height=”match_parent”layout=”@layout/title”/>如果你要重寫< include>標簽指定布局的布局屬性,那么必須重寫android:layout_height及android:layout_width這兩個屬性,以便使其它屬性的作用生效。
使用< merge>標簽
在將一個布局內嵌進另一個布局時,< merge>標簽可以幫助消除冗余的View容器。舉個例子,如果你的主布局是一個垂直的LinearLayout,在它的內部含有兩個View,并且這兩個View需要在多個布局中重用,那么重用這兩個View的布局需要有一個root View。然而,使用單獨的LinearLayout作為這個root View會導致在一個垂直的LinearLayout中又嵌了一個垂直的LinearLayout。其實這個內嵌的LinearLayout并不是我們真正想要的,此外它還會降低UI性能。
為了避免出現這種冗雜的View容器,你可以使用< merge>標簽作為這兩個View的root View:
<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>那么現在再使用這個布局的時候,系統會自動忽略< merge>標簽,并會將兩個Button View直接加入到布局< include/>標簽所指定的位置。
總結
以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:布局性能优化之布局复用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【LeetCode】3月25日打卡-Da
- 下一篇: Android官方开发文档Trainin