Cody Blog

使用 Style 或 Theme 修改 Android 元件的外觀

前言

在 Android 中有 styletheme 兩種不同方式來設定元件的外觀

Style

res/values/styles.xml 新增一個 style 標籤,讓View的背景顯示為深藍色:

<resources>
    ...
    <style name="BeatBoxButton">
        <item name="android:background">@color/dark_blue</item>
    </style>
</resources>

使用方式則是在想套用這個 stytle 的 view 物件上加上 style 屬性:

<Button
    ...
    style="@style/BeatBoxButton.Bold"/>

這麼做的好處就是當應用程式如果有很多 button,若是要換別的顏色的話,就只要更新 style 就好了。

Style inheritance

另外 style 跟 class 一樣有繼承的使用方式

方法一:

加上 parent 的屬性:

<style name="MyButtonStrong" parent="MyBoxButton">
    <item name="android:textStyle">bold</item>
</style>

方法二:

在 Parent 的名稱後面直接加上 .,例如: "MyButton.Bold"

<style name=MyBoxButton.Bold">
    <item name="android:textStyle">bold</item>
</style>

兩這種方法都可以達到 style inheritance 的效果

Theme

針對整體性的 style,如果 app 有 100 個按扭,那麼要在每一個按扭都加上 style 的話,那就太麻煩了。所以 Android 有另一種 Theme 的機制,可以一次修改所有元件的外觀。

在 AndroidManifest.xml,預設會使用 @style/AppTheme 這個 tehme:

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

代表我們這個 App 是使用 AppTheme 的 theme

範例1,修改整個 Application button 的樣式

比如說我想要修改全部 button 的 style。修改 styles.xml:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
    <item name="android:buttonStyle">@style/BeatBoxButtonTheme</item>
</style>

<!-- theme way-->
<style name="BeatBoxButtonTheme" parent="@android:style/Widget.Holo.Light.Button">
    <item name="android:background">@color/dark_blue</item>
    <item name="android:textStyle">bold</item>
</style>

這樣所有的按鈕就會自動套用 style 而不用一個一個設定了,這就是使用 Theme 的好處 :)

範例2,修改整個 Application text 的樣式

<style name="AppTheme"
    <item name="android:textColor">@color/black</item>
</style>

<style name="button" parent="@style/Widget.AppCompat.Button">
    <!--<item name="android:background">@android:color/white</item>-->
    <!--<item name="android:textColor">@color/blue</item>-->
    <!--<item name="android:textSize">16sp</item>-->
</style>

Reference

Android

Related Posts

Comments