Android 系統在 themes.xml 和 style.xml (\base\core\res\res\values\) 中預定義了大量主題與樣式。開發者應優先挑選合適的系統樣式繼承修改,而非從零編寫。
| 主題名 | 含義與適用場景 |
|---|---|
| Theme | 默認主題,不指定屬性時生效 |
| Theme_NoDisplay | 不顯示任何內容,適用於無 UI 的後台 Activity |
| Theme_NoTitleBar | 無標題欄,默認黑色背景 |
| Theme_NoTitleBar_Fullscreen | 無標題欄全屏,默認黑色背景 |
| Theme_Black | 黑色背景默認主題 |
| Theme_Black_NoTitleBar | 黑色背景無標題欄 |
| Theme_Black_NoTitleBar_Fullscreen | 黑色背景無標題欄全屏 |
| Theme_Light | 亮色背景默認主題 |
| Theme_Light_NoTitleBar | 亮色背景無標題欄 |
| Theme_Light_NoTitleBar_Fullscreen | 亮色背景無標題欄全屏 |
| Theme_Dialog | 對話框風格,Activity 以彈窗形式展示 |
| Theme_Panel | 純矩形面板,移除所有窗口裝飾 |
| Theme_Light_Panel | 亮色版純面板 |
| Theme_Wallpaper | 以壁紙為背景 |
| Theme_Wallpaper_NoTitleBar | 壁紙背景無標題欄 |
| Theme_Wallpaper_NoTitleBar_Fullscreen | 壁紙背景無標題欄全屏 |
| Theme_Translucent | 半透明背景,顯示上一層畫面 |
| Theme_Translucent_NoTitleBar | 半透明無標題欄 |
| Theme_Translucent_NoTitleBar_Fullscreen | 半透明無標題欄全屏 |
本質是將佈局 XML 中重複的屬性提取到樣式文件復用。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="TextStyle">
<item name="android:textSize">14sp</item>
<item name="android:textColor">#fff</item>
</style>
</resources>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
style="@style/TextStyle" />
兩種實現方式:
<style name="TextTitle" parent="TextStyle">...</style><style name="TextStyle.TextTitle">...</style>(父樣式名.子樣式名)<!-- 基礎文本樣式 -->
<style name="TextStyle">
<item name="android:shadowDx">-0.5</item>
<item name="android:shadowDy">1</item>
<item name="android:shadowRadius">0.5</item>
<item name="android:singleLine">true</item>
<item name="android:ellipsize">marquee</item>
</style>
<!-- 標題樣式繼承基礎樣式 -->
<style name="TextTitle" parent="TextStyle">
<item name="android:textSize">18sp</item>
<item name="android:textColor">#fff</item>
<item name="android:textStyle">bold</item>
</style>
優點:避免重複定義陰影、單行、溢出處理等通用屬性,維護性極強。點號法命名隨層級加深名稱變長,建議項目中統一規範使用 parent 屬性。
善用系統 Theme 可快速實現無標題、全屏、對話框、透明等窗口效果;Style 抽離 View 共同屬性配合繼承機制,能大幅減少佈局代碼冗餘,提升 UI 一致性與可維護性。