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

Android 自訂 Style:讓樣式設定擺脫重複

編輯:關於 Android 程式設計

同一組字型大小、顏色、寬高反覆寫在每個配置檔裡,是版面維護失控的起點。Style 就是把這些屬性抽成一份可重複引用的樣式定義,概念等同 CSS 的 class。

定義樣式

在 res/values/styles.xml 中宣告。除了自訂樣式,這裡也能看到 Android 專案預設產生的樣式繼承鏈:

<resources xmlns:android="https://schemas.android.com/apk/res/android">

    <style name="AppBaseTheme" parent="android:Theme.Light">
    </style>

    <style name="AppTheme" parent="AppBaseTheme">
    </style>

    <!-- 自訂樣式 -->
    <style name="testStyle">
        <item name="android:textSize">30px</item>
        <item name="android:textColor">#1110CC</item>
        <item name="android:width">150dip</item>
        <item name="android:height">150dip</item>
    </style>

</resources>

每個 <item> 的 name 就是你在配置檔中會寫的屬性名稱,只是把 android: 前綴搬到 name 裡。若要建立繼承關係,用 parent 屬性指向另一個 style 即可,如上例的 AppTheme 繼承 AppBaseTheme。

在配置檔中套用

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        style="@style/testStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />
</RelativeLayout>

Activity 端

套用 style 之後,Java 程式碼完全不需要改動,一切都在宣告式版面裡完成:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

幾個實務建議

樣式的價值在規模變大後才顯現。建議從「同一畫面內重複三次以上」的屬性組合開始抽,並依用途命名(如 TextLabel.Small.Gray),而不是依外觀命名(如 Style12),否則設計一改就名不符實。另外,Style 與 Theme 的分工要清楚:Style 修飾單一檢視,Theme 則是套給整個 Activity 或應用的預設外觀,透過 android:theme 指定。兩者搭配得當,換版或改配色時往往只需改一個檔案。

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