在我們開發android布局時,經常會有很多的布局是相同的,這個時候我們可以通過<include/>和<merge/>標籤實現將複雜的布局包含在需要的布局中,減少重複代碼的編寫。
1. 建立一個可以重複使用的布局:
如下代碼描述在應用中每個acitivity都出現的頂欄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:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/gafricalogo" /></FrameLayout>
上面的根布局(root view)即frameLayout會出現在之後插入的地方。
2. 使用<include/>標籤:
在應用中的一個activity的布局中頂欄就是如上的布局,那麼我們就可以include上面的titlebar.xml達到複用的效果,布局代碼如下
<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 android:id="@+id/new_title" layout="@layout/titlebar"/> <TextView android:layout_width=”match_parent” android:layout_height="wrap_content" android:text="@string/hello" android:padding="10dp" /> ...</LinearLayout>
通過取得元素的id,我們可以修改include標籤中元素的屬性,下面的例子為在actiivty中修改titlebar中的圖片:
private View mTitleBar = null;private ImageView mTitleImageView = null;mTitleBar = findViewById(R.id.new_title);mTitleImageView = (ImageView)mTitleBar.findViewById(R.id.title);mTitleImageView.setImageResource(R.drawable.logo);
在使用include標籤時,我們可以覆寫插入布局root view的屬性(所有的android:layout_*屬性)
<include android:id=”@+id/news_title” android:layout_width=”match_parent” android:layout_height=”match_parent” layout=”@layout/title”/>
如果需要覆寫插入布局root view的屬性,則必須制定android:layout_width和android:layout_height這兩個屬性以使其它的覆寫屬性生效。
3. 使用<merge/>標籤
merge標籤用來消除我們在include一個布局到另一個布局時所產生的冗餘view group。比如現在很多布局中會有兩個連續的Button,於是我們將這兩個連續的Button做成可複用布局(re-usable layout)。在使用include標籤時我們必須先將這兩個Button用一個view group比如LinearLayout組織在一起然後供其它布局使用,如果是include的地方也是LiearLayout就會造成有兩層連續的LiearLayout,除了降低UI效能沒有任何好處。這個時候我們就可以使用<merge/>標籤作為可複用布局的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>
當我們用<include/>標籤複用上述代碼時,系統會忽略merge元素,直接將兩個連續的Button放在<include/>標籤所在處。