樣式(style)是屬性的集合,用來指定View或者Window的外觀和格式。html
這些屬性能夠是height(高度)、padding(內邊距)、font size(字體顏色)等。android
樣式定義在另外一個xml文件中,從佈局文件中分離出來。app
例如:ide
1 <TextView 2 android:layout_width="fill_parent" 3 android:layout_height="wrap_content" 4 android:textColor="#00FF00" 5 android:typeface="monospace" 6 android:text="@string/hello" />
若是使用樣式,則能夠轉換爲佈局
1 <TextView 2 style="@style/CodeFont" 3 android:text="@string/hello" />
CodeFont就是樣式文件名,把一些屬性從原佈局文件中提取出來,存放到了CodeFont文件中。post
樣式文件必須存放在res/valuse的文件夾中,命名任意,後續爲.xml。字體
CodeFont.xmlui
1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 <style name="CodeFont" parent="@style/BaseFont"> 4 <item name="android:layout_width">fill_parent</item> 5 <item name="android:layout_height">wrap_content</item> 6 <item name="android:textColor">#00FF00</item> 7 <item name="android:typeface">monospace</item> 8 </style> 9 </resources>
<resources>:根元素。google
<style>:屬性集合。url
<item>:屬性。
使用parent,能夠繼承樣式。除此以外,還能夠在<style>的命名前添加"繼承樣式名.",效果同樣。例如:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="BaseFont.CodeFont" > <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textColor">#00FF00</item> <item name="android:typeface">monospace</item> </style> </resources>
注意:
引用此樣式時的名字爲BaseFont.CodeFont。
若是引用系統自帶的樣式,值的格式爲「@android:style/樣式名」。咱們自定義的樣式,值的格式爲「@style/樣式名」。
對單獨的View,舉例:
佈局文件中,<TextView style="@style/CodeFont" android:text="@string/hello" />
對整個Activity或整個應用程序,舉例:
AndroidManifest.xml文件中,<activity android:theme="@android:style/Theme.Dialog">或者<application android:theme="@style/CustomTheme">