Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 主題(Theme)切換實作教學

編輯:關於 Android 程式設計

為 App 提供多套主題皮膚,是提升使用者體驗常見的做法。Android 透過自訂屬性與 Style 的配合,就能實現靈活的主題切換。本文示範從定義屬性、編寫 Style 到動態讀取主題值的完整流程。

一、定義自訂屬性

首先在 attrs.xml 中宣告一個可樣式化屬性集合:

<resources>
    <declare-styleable name="my_styleable">
    </declare-styleable>
</resources>

二、定義對應的 Style

接著在 styles.xml 中定義具體主題,把屬性指向實際的顏色與圖片資源:

<style name="Bule" parent="@android:style/Theme.Light.NoTitleBar">
    <item name="colorValue">@color/bule_bg</item>
    <item name="backValue">@drawable/icon_bule_back</item>
</style>

三、在布局中引用屬性

使用時,透過 ?attr/ 語法引用自訂屬性,而非寫死具體值:

<TextView
    android:id="@+id/tv_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="測試文字"
    android:textColor="?attr/colorValue"
    android:textSize="28sp" />

四、在 Activity 中套用主題

別忘了在 onCreate 中、且必須在 setContentView 之前呼叫 setTheme:

setTheme(R.style.Bule);
// 注意:一定要在 setContentView 之前設定主題
setContentView(R.layout.activity_main);

五、動態讀取當前主題的屬性值

當我們做了兩款以上主題,需要取得當前主題某個屬性的實際值(例如 tv_test 的 textColor)時,可透過 obtainStyledAttributes 讀取:

TypedArray ta = getTheme().obtainStyledAttributes(R.styleable.my_styleable);
// R.styleable.my_styleable_colorValue 是自動生成的
int color = ta.getColor(R.styleable.my_styleable_colorValue, 0);
// 別忘了回收
ta.recycle();

透過這套「自訂屬性 + Style + setTheme」的組合,就能輕鬆實現多主題切換,並在需要時動態取得主題相關的屬性值。

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