Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android UI 進階:Style 與 Theme 的定義、繼承與套用

編輯:Android 開發實例

Style 與 Theme 是 Android 介面設計裡最容易被忽略、卻最能省下大量重複勞動的兩件事。兩者本質相同——都是資源的集合,只是作用範圍不同。

一、定義方式與差別

Android 本身提供了許多現成的 style 與 theme 可直接取用,同時也允許我們自訂。做法是在 res/values/ 底下新增一個 .xml 檔,根節點必須是 <resources>,每個樣式用 <style> 元素宣告並取一個全域唯一的名字,可選地加上 parent 屬性來繼承既有樣式。

兩者的定義格式完全一樣,差別在套用範圍:

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

這份樣式取名為 CodeFont,parent 指向系統內建的 TextAppearance.Medium,因此它會先繼承父樣式的屬性,再套上這裡覆寫的四項。

父樣式也可以是自己定義的,寫法有兩種:一是仍用 parent 屬性;二是用「點」串接名稱,例如 ContFont.red,還能再往下層級 ContFont.red.small,形成類似階層繼承的效果。

每個 <item> 就是一個屬性。想知道某個 View 有哪些屬性可寫,最可靠的方式是查 API 文件裡該 View 的 XML 屬性表——例如 EditText 有 inputType,那麼在你的 style 裡就能設定它。

三、套用 Style

在布局檔裡掛上 style 屬性即可:

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

四、Theme 的註冊與套用

Theme 必須在 AndroidManifest.xml 中註冊。要讓整個程式都套用:

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

只想讓某個 Activity 使用,就寫在該 Activity 標籤上:

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

這會让整个 Activity 變成對話框的形式。若想要透明背景:

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

系統內建的好用主題還不少,例如 Theme.Light(淺色底)、Theme.NoTitleBar(無標題列)、Theme.Black.NoTitleBar.Fullscreen(全螢幕)等,先從中挑一個再繼承,往往比自己從零調快得多。

五、自訂 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>

這裡有個值得學的小技巧:?panelForegroundColor 這種「問號前綴」是在引用屬性值,而 @ 前綴是引用資源。先定義好前景色,再讓文字色、選單文字色一併指向它,之後要換配色只改一處就好。

六、在程式碼中載入 Theme

setTheme(R.style.CustomTheme);

若要在 Java 端套用主題,這行必須放在任何 View 初始化之前,也就是一定要先於 setContentView()。不過一般不建議這麼做——把主題寫在 Manifest 裡更清楚,也更不容易出錯。

寫布局時熟練地運用 style 與 theme,不只是省事:當同一份樣式散落在各個檔案裡時,改一次配色要動幾十個地方;抽成樣式後,改一行就全域生效。這正是資源化設計的價值所在。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved