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

Style.xml 的妙用:讓 Android 版面檔擺脫重複屬性

編輯:關於 Android 程式設計

Style.xml 之於 Android,有點像 CSS 之於網頁——把重複的屬性抽出來集中管理。很多老手的版面檔看起來特別乾淨,祕然往往就在這裡。

對比一下就很明顯

常見的寫法是把寬高屬性一個一個寫在標籤上:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView android:id="@+id/sensor"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

這樣寫功能上完全沒問題,但每個標籤都得重複一次寬高,行數多了就很囉嗦。改成引用 style 之後:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" >
    <TextView android:id="@+id/sensor" style="@style/all_match" />
</LinearLayout>

不但省字,一眼還能看出這個元件用了哪種尺寸策略。

先把常用的幾個 style 準備好

在 res/values/styles.xml 裡定義幾個通用樣式:

<style name="all_fill">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">fill_parent</item>
</style>

<style name="all_match">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
</style>

<style name="width_fill">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
</style>

<style name="height_fill">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">fill_parent</item>
</style>

補充一點:原文範例中的 match_content 並不是合法值,正確寫法應為 match_parent(填滿父層)或 wrap_content(依內容自適應),這裡已修正。fill_parent 與 match_parent 效果相同,前者是舊名稱,目前建議統一用 match_parent。

style 的進階玩法

除了寬高,style 更適合管理「一整組視覺設定」。例如把按鈕的字級、字色、內距、背景一起打包:

<style name="MainButton">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">48dp</item>
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">@android:color/white</item>
    <item name="android:background">@drawable/bg_button</item>
</style>

還可以透過 parent 屬性做繼承,只覆寫想改的部分:

<style name="MainButton.Red" parent="MainButton">
    <item name="android:background">@drawable/bg_button_red</item>
</style>

命名上用「點」分隔的慣例,Android Studio 會自動辨識為繼承關係,改動起來一目了然。另外若樣式是給整組元件共用(例如整頁按鈕都長一樣),也可以在 Theme 裡用 <item name="android:buttonStyle">@style/MainButton</item> 一次套用。

把樣式抽乾淨之後,版面檔的結構會清楚很多,後續要調整視覺規格也只需改一個檔案。以上就是 Style.xml 的實用做法,希望對大家的專案維護有所幫助。

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