Android提供了許多可視的組件。通過自訂樣式和主題,可以避免用這些組件開發的應用看上去千篇一律。
樣式和主題都是通過預定義一系列屬性值來形成統一的顯示風格。區別是,樣式只能應用於某種類型的View;而主題剛好相反,它不能應用於特定的View,而只能作用於一個或多個Activity,或是整個應用。
以下結合具體例子說明如何定義樣式和主題:
1.定義樣式和主題
在工程中res/values/下添加styles.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <!-- 定義my_style_1,沒有指定parent,用系統預設的 -->
- <style name="my_style_1">
- <!-- 定義與指定View相關的若干屬性 -->
- <item name="android:hint">load from style 1</item>
- </style>
- <!-- 定義my_style_2,用自訂的my_style_1作為parent -->
- <style name="my_style_2" parent="@style/my_style_1">
- <!-- 定義與指定View相關的若干屬性 -->
- <item name="android:textSize">30sp</item>
- <item name="android:textColor">#FFFF0000</item>
- <item name="android:hint">load from style 2</item>
- </style>
- <!-- 定義my_style_3,用android的EditText作為parent -->
- <style name="my_style_3" parent="@android:style/Widget.EditText">
- <!-- 定義與指定View相關的若干屬性 -->
- <item name="android:hint">"load from style 3"</item>
- <item name="android:textStyle">bold|italic</item>
- <item name="android:typeface">monospace</item>>
- <item name="android:background">@drawable/mybackground</item>
- </style>
- <!-- 定義MyTheme,用android的Theme作為parent -->
- <style name="MyTheme" parent="@android:style/Theme">
- <item name="android:textSize">20sp</item>
- <item name="android:textColor">#FF0000FF</item>
- <item name="android:hint">"load from style 3"</item>
- <item name="android:textStyle">bold|italic</item>
- <item name="android:typeface">monospace</item>>
- <item name="android:background">@drawable/gallery_selected_pressed</item>
- <item name="myStyle">@style/my_style_3</item>
- </style>
- </resources>
複製代碼
主題和樣式的定義方法類似,都是在<style>下添加N個<item>。
<style>下有兩個有用的屬性:
name - 以後引用時會用到;
parent - 可選,一些在自訂的style中沒有指定的屬性會繼承parent style中的值。parent可以是android預定義的resource,也可以是自己定義的style。
<item>下定義需要改變的屬性值。Android中能使用的屬性可以在<sdk>/docs/reference/android/R.styleable.html中查到;也可以用自己定義的屬性值;
2.使用主題
a)從AndroidManifest中指定,可以選擇Application應用級:
- <application android:theme="@style/MyTheme">
複製代碼
或是Activity級:
- <activity android:theme="@style/MyTheme">
複製代碼
b)從Java代碼中指定:
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setTheme(R.style.MyTheme);
- setContentView(R.layout.main);
- }
複製代碼
注意:setTheme必須在setContentView(),addContentView()或inflate()等執行個體化View的函數之前調用!
3.使用樣式
a)從layout的xml檔案中指定:
- <EditText android:id="@+id/EditText03"
- style="@style/my_style_3"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- </EditText>
複製代碼
b)從Java代碼中指定:
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setTheme(R.style.MyTheme);
- setContentView(R.layout.main);
- LinearLayout ll = (LinearLayout)findViewById(R.id.llMain);
- EditText et = new EditText(this, null, R.attr.myStyle);
- ll.addView(et);
- }
複製代碼
-----------------
附件中是用到的具體例子
referenece:<android-sdk-windows-1.5_r2>/docs/guide/topics/ui/themes.html