如果我們在每個xml文件中都把相同的布局都重寫一遍,一個是代碼冗余,可讀性很差;另一個是修改起來比較麻煩,對后期的修改和維護非常不利。所以,一般情況下,我們需要把相同布局的代碼單獨寫成一個模塊,然后在用到的時候,可以通過<include /> 標簽來重用layout的代碼。
常見的,有的應用在最上方會有一個標題欄。類似下圖所示。
圖 標題欄的示例
如果項目中大部分Activity的布局都包含這樣的標題欄,就可以把標題欄的布局單獨寫成一個xml文件。 android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:background="@drawable/navigator_bar_bg" xmlns:android="http://schemas.android.com/apk/res/android"> <TextView android:id="@android:id/title" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:gravity="center" android:hint="title" android:textAppearance="?android:attr/textAppearanceMedium" /> <ImageView android:id="@android:id/closeButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:src="@drawable/close" /> </RelativeLayout> 一般情況下,在項目的初期就能夠大致確定整體UI的風格。所以早期的時候就可以做一些規(guī)劃,將通用的模塊先寫出來。 下面是可能可以抽出的共用的布局: 1)背景。有的應用在不同的界面里會用到統(tǒng)一的背景。后期可能會經(jīng)常修改默認背景,所以可以將背景做成一個通用模塊。 2)頭部的標題欄。如果應用有統(tǒng)一的頭部標題欄,就可以抽取出來。 3)底部的導航欄。如果應用有導航欄,而且大部分的Activity的底部導航欄是相同的,就可以將導航欄寫成一個通用模塊。 4)ListView。大部分應用都會用到ListView展示多條數(shù)據(jù)。項目后期可能會經(jīng)常調(diào)整ListView的風格,所以將ListView作為一個通用的模塊比較好。
<RelativeLayout
我們將上面的xml文件命名為“navigator_bar.xml”,其它需要標題欄的Activity的xml布局文件就可以直接引用此文件了。
<include layout="@layout/navigator_bar" />
經(jīng)驗分享:
新聞熱點
疑難解答
圖片精選