Android的風格設計(style)是一個很重要的功能,因為它可以讓應用程序裡的控件(widget)個性化。風格設計的使用如下:
在Android的項目裡以XML的資源來定義風格
一個Android項目可以定義多個風格
讓widget套用其中的一個樣式
Android的style功能,主要的對象是widget,風格是為瞭套用到widget上;另外Android提供佈景(theme)功能,可以做更大范圍的套用。
下面是一個風格定義的具體例子:
在/res/values/目錄下建立一個新文件style.xml,編輯內容如下:
[html] <?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="myText">
<item name="android:textSize">18sp</item>
<item name="android:textColor">#00FF00</item>
</style>
<style name="myButton">
<item name="android:background">#00BFFF</item>
</style>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="myText">
<item name="android:textSize">18sp</item>
<item name="android:textColor">#00FF00</item>
</style>
<style name="myButton">
<item name="android:background">#00BFFF</item>
</style>
</resources>
style.xml語法說明:
在<resource>標簽定義資源項目,<style>標簽用來定義風格資源;
<style>的name屬性定義風格名稱,widget使用此名稱套用;
<item>標簽定義此風格的內容;
textSize —— 字體大小
textColor —— 字體顏色
background —— 背景
更多,參考Android Reference
定義好style後,就可以讓widget套用。
讓widget套用定義好的style方法很簡單,隻需在main.XML中的widget項目屬性添加定義好的style name就可以瞭,編輯main.XML:
[html] <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
style="@style/myText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/btn"
style="@style/myButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
style="@style/myText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/btn"
style="@style/myButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
程序執行效果:
摘自 Young的專欄