在android佈局中使用include和merge標籤
在我們開發android佈局時,經常會有很多的佈局是相同的,這個時候我們可以通過和標籤實現將複雜的佈局包含在需要的佈局中,減少重複代碼的編寫。
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. 使用標籤:
在應用中的一個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性能沒有任何好處。這個時候我們就可以使用標籤作爲可複用佈局的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>