萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Style 機制深度解析與實戰技巧

前言

Android 樣式系統支援屬性集中定義、繼承、主題屬性引用與版本限定,是打造一致 UI 的核心機制。本文深入解析 Style 結構、常見屬性、主題與樣式關係及實戰技巧。

Style 基本結構

<resources>
    <style name="DavidStyleText1">
        <item name="android:textSize">18sp</item>
        <item name="android:textColor">#EC9237</item>
    </style>

    <style name="DavidStyleText2">
        <item name="android:textSize">14sp</item>
        <item name="android:textColor">#FF7F7C</item>
        <item name="android:alpha">0.5</item> <!-- 透明度 -->
    </style>
</resources>

Style vs Theme

特性StyleTheme
作用範圍單一 View 或 ViewGroup整個 Activity、Application 或 View 層級 (android:theme)
定義位置res/values/styles.xmlres/values/themes.xml (同一檔案亦可)
屬性型別View 屬性 (layout_width, textColor...)主題屬性 (colorPrimary, windowBackground, textAppearance...)
引用語法@style/StyleName@style/ThemeName 或 ?attr/attrName

繼承與覆寫機制

  • 隱式繼承:name="Parent.Child" 自動繼承 Parent 所有 item。
  • 顯式繼承:parent="Parent" 明確指定。
  • 多層繼承:Base → Heading → Heading.Title,層層疊加。
  • 覆寫規則:子 Style 同名 item 會覆蓋父 Style;若需保留父值並追加,需在子項完整重寫。

主題屬性引用 (Theme Attributes)

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <item name="colorPrimary">#1A73E8</item>
    <item name="colorOnPrimary">@android:color/white</item>
    <item name="textAppearanceHeadline6">@style/CustomHeadline6</item>
</style>


<TextView
    android:textAppearance="?attr/textAppearanceHeadline6"
    android:text="標題" />

版本限定與裝置適配

  • res/values-v21/styles.xml:API 21+ 專屬 Material 風格覆寫。
  • res/values-night/styles.xml:夜間模式專屬色系。
  • res/values-sw600dp/styles.xml:平板/大螢幕專屬尺寸。

實戰技巧

  1. 統一尺寸規範:定義 dimen.xml 並用 @dimen/spacing_m 替代硬編碼。
  2. 文字外觀體系:建立 TextAppearance.Headline1 ~ Caption 階層,統一字體、大小、字重、行高。
  3. 元件風格化:為 Button、CardView、Chip 定義預設 Style,在 Theme 中指定 buttonStyle、chipStyle 等屬性全域生效。
  4. 動態換膚:結合 MaterialThemeOverlay 或自訂 ContextThemeWrapper 運行時切換 Theme。

常見問題

Q: Style 中設定 layout_width 無效?
A: LayoutParams 屬性不支援透過 Style 設定,必須直接寫在 XML 標籤或程式碼中。
Q: 為何夜間模式不生效?
A: 確認 Theme 繼承 DayNight,且 values-night 目錄命名正確;AppCompat 1.1+ 需呼叫 AppCompatDelegate.setDefaultNightMode()。

精通 Style 機制,能建立可維護、可擴充、多主題適配的 UI 體系。

copyright © 萬盛學電腦網 all rights reserved