編輯:關於 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>
不但省字,一眼還能看出這個元件用了哪種尺寸策略。
在 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 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 的實用做法,希望對大家的專案維護有所幫助。
Android 環境變數設定教學:解決「android 不是內部或外部命令」
建立 AVD 時在命令列輸入 android list targets,卻跳出「android 不是內部或外部命令」的提示,這幾乎都是 Android SDK 環境變數沒
CoordinatorLayout 完全指南:Behavior 機制與三種典型組合
一、CoordinatorLayout 的定位 官方把它稱為「super-powered FrameLayout」,核心職責只有兩件事:作為頂層容器,以及調度協調子布局。
Android 開發 Tips(3):10 個提升效率的工具與寫法
這一則是零碎但實用的小技巧合集,涵蓋測試工具、Android Studio 插件、網路層寫法與效能優化,每一項都拿去就能用。 1. UIAutomatorViewer:
Android Shape 與 Selector 結合:自訂控制項狀態背景
在 Android UI 設計中,shape 用來描述幾何外觀,selector 則用來描述不同狀態下的顯示結果。兩者結合後,可以做出圓角按鈕、列表項選取效果與狀態背景。