一、樣式布局
首先,先看下面這段樣式布局代碼,這里稱在xml控件上添加屬性為內聯(僅限於本篇博文這樣稱呼):
<Button android:id="@+id/crime_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp"/> <CheckBox android:id="@+id/crime_solved" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:text="@string/solved_btn"/> <Button android:id="@+id/choose_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:text="@string/choose_name"/> <Button android:id="@+id/contact_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:text="@string/contacter_name"/>
在上面這段XML布局代碼,可以看出,各個按鈕的樣式完全一樣,添加某個屬性給控件就有多次。假如,有更多的控件使用相同的而已,要做N次重復的工作。Android提供了各種樣式UI,可用於解決重復性的工作。樣式資源類似於CSS樣式。樣式也可以具有層級結構:子樣式擁有父式樣同樣的屬性及屬性值,可以覆蓋它們,也可以添加新的屬性。
類似字符資源,樣式定義在XML文件的<Resources>酬標簽內,並存放在res/values目錄中。另外,資源文件取什么名並不重要,但根據約定,樣式通常定義在style.xml文件中。在Android項目中,已經默認創建了這個文件。
Style.xml文件:
1 <resources> 2 <style name="Crime_btn_style1"> 3 <item name="android:layout_width">wrap_content</item> 4 <item name="android:layout_height">wrap_content</item> 5 <item name="android:layout_marginLeft">16dp</item> 6 <item name="android:layout_marginRight">16dp</item> 7 </style> 8 </resources>
layout/fragment_crime.xml文件,將控件的屬性以style樣式名引入的方式在外聯(僅限於本篇博文這樣稱呼):
1 <Button 2 android:id="@+id/crime_date" 3 style="@style/Crime_btn_style1"/> 4 5 <CheckBox 6 android:id="@+id/crime_solved" 7 android:text="@string/solved_btn" 8 style="@style/Crime_btn_style1"/> 9 10 <Button 11 android:id="@+id/choose_btn" 12 android:text="@string/choose_name" 13 style="@style/Crime_btn_style1"/> 14 15 <Button 16 android:id="@+id/contact_btn" 17 android:text="@string/contacter_name" 18 style="@style/Crime_btn_style1"/>
PS:需要注意的是,在內聯屬性與外聯屬性沖突時,以內聯屬性為准,也可以說,內聯屬性優於外聯屬性方式。
二、include與merge
include使用資源ID引入而已文件。
layout/button_row.xml
1 <TableRow 2 xmlns:android="http:/schemas.android.com/apk/res/android"> 3 <Button style="@style/Crime_btn_style1"> 4 <Button style="@style/Crime_btn_style1"> 5 <Button style="@style/Crime_btn_style1"> 6 </TableRow>
layout/fragment_crime.xml
1 <include 2 android:layout_weight="1" 3 layout="@layout/button_row" /> 4 <include 5 android:layout_weight="1" 6 layout="@layout/button_row" /> 7 <include 8 android:layout_weight="1" 9 layout="@layout/button_row" />
以上代碼表明,include將引入資源ID為button_row文件內容。
PS:include標簽只能引用layout布局文件,也就是只能引用layout目錄下的布局文件。