1.概述
style是屬性的集合,用來指定view或者window的外觀和版式。style可以指定諸如高度,填充,字型顏色,字型大小,背景顏色等屬性。style定義在與layout檔案分開的xml資源檔中。
例如可以如下使用style:
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#00FF00" android:typeface="monospace" android:text="@string/hello" />
使用style之後:
<TextView style="@style/CodeFont" android:text="@string/hello" />
所有的style屬性都被從layout xml檔案中移除,然後寫到一個style xml檔案中,命名為:
CodeFont。
theme是一種style,運用在所有的activity或者application。
2.建立style
在工程目錄res/values/下,建立一個檔案,名字隨意,儲存style屬性集。xml檔案的根節點必須是<resources>。
例子如下:
<?xml version="1.0" encoding="utf-8"?><resources> <style name="CodeFont" parent="@android:style/TextAppearance.Medium"> <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>
在編譯的時候
<resources>的子項目都會被轉換成一個application資來源物件。可以通過name來引用。
parent屬性可選,可以指定為另一個style檔案的id。
3.繼承
<style>元素中的parent屬性可以指定一個style,我們的定義的style繼承於這個style。可以使用這一屬性繼承已有的style,而只用定義或者改變部分的屬性。
<style name="GreenText" parent="@android:style/TextAppearance"> <item name="android:textColor">#00FF00</item> </style>
比如上面例子,繼承了TextAppearance,修改了textColor屬性。
如果是使用繼承自己定義的style,就沒有必要使用parent屬性了。只需要在你的新style的名字前加上已定義的style的名字。例子如下:
<style name="CodeFont.Red"> <item name="android:textColor">#FF0000</item> </style>
4.style的屬性值
現在已經知道如何定義一個屬性檔案了,下面來看看在style檔案中可以定義那些屬性item。查看指定view的屬性的最好的方法就是查看class 參考文檔。比如TextView所有可利用的屬性都在TextView XML attributes列出來了。
參考文檔http://developer.android.com/guide/topics/ui/themes.html#PlatformStyles