首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Android Style 與 Theme 完整指南:從 XML 定義到應用層級主題切換

     編輯:Java 相關知識

Style:View 層級樣式複用

在 res/values/styles.xml 定義:

<resources>
  <style name="MyText" parent="@android:style/TextAppearance">
    <item name="android:textColor">#987456</item>
    <item name="android:textSize">24sp</item>
  </style>
</resources>
  • parent:繼承現有樣式,可覆寫屬性
  • 使用:<EditText style="@style/MyText" .../>

Theme:Activity/Application 層級主題

<style name="CustomTheme" parent="@android:style/Theme">
  <item name="android:windowNoTitle">true</item>
  <item name="android:windowFrame">@drawable/icon</item>
  <item name="android:windowBackground">?android:windowFrame</item> <!-- 引用同主題其他項 -->
</style>

三種套用方式

1. AndroidManifest.xml 應用級

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

2. AndroidManifest.xml Activity 級

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

3. 程式碼動態切換

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle saved) {
        setTheme(R.style.CustomTheme); // 必須在 setContentView 之前
        super.onCreate(saved);
        setContentView(R.layout.main);
    }
}

Style vs Theme 差異對比

維度StyleTheme
作用範圍單一 View整個 Activity 或 Application
屬性前綴直接屬性名通常以 window、color 開頭
繼承關係View 樣式繼承系統主題繼承
動態切換不支援支援(onCreate 前)

進階技巧

  • ?attr/name 引用主題屬性:<item name="android:background">?attr/colorPrimary</item>
  • Material Components 主題:Theme.MaterialComponents.Light.DarkActionBar
  • 夜間模式:AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES)
  • 自訂屬性:attrs.xml 定義 <attr name="customColor" format="color"/>,Style 中引用

常見坑點

  1. setTheme 必須在 super.onCreate() 之前,否則不生效
  2. Theme 屬性名錯誤(如漏寫 android: 前綴)導致不生效
  3. Style 繼承非 View 類別父樣式導致屬性不匹配
  4. Application 級 Theme 被 Activity 級覆蓋時優先序混淆
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved