android UI進階之style和theme的使用

今天來和大家分享一下android中UI設計裏面常會用到的style和theme。

首先,style和theme都是資源,android提供了很多這樣的默認資源。你可以來使用它們。同時你也可以自己定義style和 theme。這非常的簡單,只需要在res/values/這個路徑裏面新建一個.xml文件,而且他的根節點必須是<resources>.對每一個style和theme,給<style>element增加一個全局唯一的名字,也可以選擇增加一個父類屬性,我們寫的style和 theme就會繼承這個父類的屬性。style和theme的定義格式相同。不過style是針對view來說的,比如 TextView,EditText這些,而theme必須針對整個activity或者整個程序,你必須在AndroidManifest.xml中的<application>或者<activity>中定義。 

先來看看style,比如如下一段代碼:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.     <style name="CodeFont" parent="@android:style/TextAppearance.Medium"> 
  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> 

可以看到這個style的名字爲CodeFont。 parent後面就是父類的style, CodeFont繼承這個父類的屬性。可以看到這個父類的style是android中默認的,你也可以繼承你自定義的style,這時候不需要再寫 parent屬性,而是使用ContFont.red這樣的方式,而且你可以繼續繼承,寫成ContFont.red.small。 接下來每一個item定義一個屬性。定義屬性的最好方法就是在api文檔裏找到這個view的xml屬性,比如在EditText中有InputType 這個屬性,那麼在你的style裏面你就可以來定義它。

這樣一個style就寫好了。

使用也非常簡單,我們只要在寫我們的view時,加入style標籤就可以了,就像這樣

  1. <TextView 
  2.     style="@style/CodeFont" 
  3.     android:text="@string/hello" /> 

下面講講主題,前面已經說了。主題需要在AndroidManifest.xml中註冊。如果你想整個程序都使用這個主題,你可以這樣寫

  1. <application android:theme="@style/CustomTheme"> 

如果你只需要在某個Activity中使用主題,那麼只要在Activity標籤中寫入android:theme=就可以了,android有很多好的默認主題,比如

  1. <activity android:theme="@android:style/Theme.Dialog"> 

這就會使你的整個Activity變成一個對話框形式,或者,如果你希望背景是透明的,可以這樣寫

  1. <activity android:theme="@android:style/Theme.Translucent"> 

同樣的我們也可以繼承父類theme,寫法和style一樣,就不贅述了。當然,和style一樣,你也可以自己定義一個theme,寫個例子

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.  <style name="CustomTheme"> 
  4.  <item name="android:windowNoTitle">true</item> 
  5.  <item name="windowFrame">@drawable/screen_frame</item> 
  6.  <item name="windowBackground">@drawable/screen_background_white</item> 
  7.  <item name="panelForegroundColor">#FF000000</item> 
  8.  <item name="panelBackgroundColor">#FFFFFFFF</item> 
  9.  <item name="panelTextColor">?panelForegroundColor</item> 
  10.  <item name="panelTextSize">14</item> 
  11.  <item name="menuItemTextColor">?panelTextColor</item> 
  12.  <item name="menuItemTextSize">?panelTextSize</item> 
  13.  </style> 
  14. </resources> 

如果你要在java代碼中加載主題的話,只要用setTheme(R.style.CustomTheme)就可以了,不過記得一定要在初始化任何view之前,比如一定要放在我們常用的setContentView()之前。通常,我們不建議這麼做。

在寫程序佈局的時候,熟練的使用style和theme是非常必要和有益的。今天就到這裏啦。有什麼問題可以留言交流。大家春節快樂!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章