Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發實例 >> android UI進階之style和theme的使用

android UI進階之style和theme的使用

編輯:Android開發實例

今天來和大家分享一下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,比如如下一段代碼:

 

<?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>

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

 

這樣一個style就寫好了。

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

<TextView
style="@style/CodeFont"
android:text="@string/hello" />

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

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

 

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

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

 

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

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

 

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

 

 
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomTheme">
<item name="android:windowNoTitle">true</item>
<item name="windowFrame">@drawable/screen_frame</item>
<item name="windowBackground">@drawable/screen_background_white</item>
<item name="panelForegroundColor">#FF000000</item>
<item name="panelBackgroundColor">#FFFFFFFF</item>
<item name="panelTextColor">?panelForegroundColor</item>
<item name="panelTextSize">14</item>
<item name="menuItemTextColor">?panelTextColor</item>
<item name="menuItemTextSize">?panelTextSize</item>
</style>
</resources>

 

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

在寫程序布局的時候,熟練的使用style和theme是非常必要和有益的。今天就到這裡啦。有什麼問題可以留言交流。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved