不論是利用開發回是游戲開發,我們開發出來的產品,大部份的時候還是要讓更多的人來使用的。因此,除功能上的完善以外,布局上的公道而美觀也是我們需要斟酌的問題。Style和Theme的設計就是提升用戶體驗的關鍵之1。
Style和Theme都是為了改變樣式,但是2者又略有區分:
1)Style是針對窗體元素級別的,改變指定控件或Layout的樣式。
2)Theme是是針對窗體級別的,改變窗體樣式。
它們的使用是非常靈活的,可以添加系統中所帶組件的所有屬性。
下面,我們分別來看看它們是如何使用的。
首先,我們在values目錄下創建styles.xml文件,打開以后添加上1個樣式:
<?xml version="1.0" encoding="utf⑻"?> <resources> <style name="TextView"> <item name="android:textSize">18sp</item> <item name="android:textColor">#fff</item> <item name="android:shadowColor">#FF5151</item> <item name="android:shadowRadius">3.0</item> </style> <style name="TextView_Style2"> <item name="android:textSize">24sp</item> <item name="android:textColor">#FF60AF</item> <item name="android:shadowColor">#E6CAFF</item> <item name="android:shadowRadius">3.0</item> </style> </resources> |
其中,android:shadowColor是指定文本陰影的色彩,android:shadowRadius是設置陰影的半徑。設置為0.1就變成字體的色彩了,1般設置為3.0的效果比較好。
接著,我們在布局文件中添加兩個文本框,分別給他們用上這兩個樣式:
<?xml version="1.0" encoding="utf⑻"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextView_Style1" android:text="我是樣式1"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextView_Style2" android:text="我是樣式2"/> </LinearLayout> |
效果圖如圖3⑴0所示。
圖3⑴0Style樣式的使用
可以看到,這兩個文本框利用了不同的樣式,所以顯示了不同的效果。
說完了style,下面就說說Theme。Theme跟style差不多,從代碼的角度來講是1樣的,只是概念上的不同。Theme是利用在Application或Activity里面的,而Style是利用在某1個View里面的。我們還是以1個例子來看看Theme的使用。
我們首先在values目錄下創建themes.xml文件,(固然,我們也能夠在之前的styles.xml文件中直接添加)打開以后添加上1個樣式:
<?xml version="1.0" encoding="utf⑻"?> <resources> <style parent="@android:style/Theme" name="MyTheme"> <item name="android:windowNoTitle">true</item> <item name="android:windowBackground">@drawable/ball</item> </style> </resources> |
在這里,我們寫了1個繼承自系統默許的Theme的主題,里面有2個屬性,第1個屬性是設置無標題,第2個屬性是設置背景圖。然后,我們在AndroidManifest.xml文件中利用該主題:
<?xml version="1.0" encoding="utf⑻"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.chapter2" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@style/MyTheme"> <activity android:name=".Chapter2Activity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
運行的效果如圖3⑴1所示。
圖3⑴1Theme主題的使用
可以看到,我們利用的主題已生效了。標題欄被設置為了不可見,同時也設置了背景圖片。
我們可以將那些展現效果相同的視圖設置為相同的樣式或主題,提高我們開發的效力和代碼的可讀性。