編輯:關於 Android 程式設計
網上關於 Theme 與 Style「怎麼用」的教學很多,但真正令人頭疼的往往不是用法,而是自訂時踩到的各種坑:不知道該繼承哪個 parent、為什麼背景莫名多出一圈黑邊、為什麼 setTheme 一定要寫在 setContentView 之前。本文把重點放在理清 Theme 與 Style 的關係、結構,以及它們最終是怎麼被加載生效的。
一句話區分:Theme 作用於窗體與 Activity 級別,改變的是整個窗體的樣式;Style 作用於具體控件級別,改變的是單個元素的樣式。Theme 會向下影響所有支持該屬性的子成員,Style 只影響被指定的成員。
Theme 的實質也是 Style,兩者的定義格式一致,都寫在 res 目錄下自訂的 xml 中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
一個 style 至少需要 name 屬性供外部引用,內部每個 item 就是「屬性 + 值」的一對。
關於繼承,這裡有一個容易混淆的約定:
parent 屬性。<!-- 繼承上面自訂的 CodeFont -->
<style name="CodeFont.Red">
<item name="android:textColor">#FF0000</item>
</style>
<!-- 還可以繼續往下繼承 -->
<style name="CodeFont.Red.Big">
<item name="android:textSize">30sp</item>
</style>
<!-- 使用 -->
@style/CodeFont.Red.Big
這兩種繼承方式要严格區分,不要混用。
那麼 item 裡可以寫哪些屬性?如果是在定製某個控件的 style,直接查該控件或 Window 的 API 文件、或 R.attr 即可。這是一個非常實用的技能——很多人遇到「自訂 Dialog 背景周邊多了一圈黑框」就上網複製別人的 style,卻不明白人家為什麼這麼寫,其實查一下相關屬性屬性就解決了。
兩個注意事項:使用系統屬性時別忘了 android: 前綴;item 中的屬性不見得對所有 View 有效,例如 Theme 中以 window 開頭的屬性放到 View 上不會報錯,但會被安靜地忽略。
把 style 應用到 UI 主要分兩類:
style 屬性引入。注意 ViewGroup 的 style 不會向下傳遞給子 View,除非改用 theme 方式。theme 引入,會向下影響整棵視圖樹。<!-- 在系統預置主題基礎上做局部修改 -->
<color name="custom_theme_color">#b0b0ff</color>
<style name="CustomTheme" parent="android:Theme.Light">
<item name="android:windowBackground">@color/custom_theme_color</item>
<item name="android:colorBackground">@color/custom_theme_color</item>
</style>
新版本 Android 引入了大量新 Theme,舊版本並不認識。標準做法是用資源限定符按平台版本分檔:
<!-- res/values/styles.xml -->
<style name="LightThemeSelector" parent="android:Theme.Light">
...
</style>
<!-- res/values-v11/styles.xml(API 11 以上自動命中) -->
<style name="LightThemeSelector" parent="android:Theme.Holo.Light">
...
</style>
這樣同一個 APK 跑在不同設備上,系統會自動挑選合適的那份。
R.styleable。R.attr。R.style。不過 API 文件收錄未必完整,最好的辦法是直接看 framework/base 的 res 或 appcompat 的 res。另外文件中的 Theme_NoTitleBar 在 xml 引用時要寫成 @android:style/Theme.NoTitleBar。Java 中引用資源:
[package_name.]R.resource_type.resource_name
// 本應用資源可省略包名;系統資源換成 android 前綴
XML 中引用資源:
@[package_name:]resource_type/resource_name
// 例如系統資源:android:textColor="@android:color/secondary_text_dark"
引用系統資源的特殊寫法:
@*android:type/name // 可引用系統所有資源(public + private)
@android:type/name // 只能引用系統 public 資源
引用當前主題屬性:
?[package_name:][resource_type/]resource_name
// 值會隨當前主題切換而變化,常見於動畫等場景
建立或引用資源標識:
@+type/name // 若標識已存在則引用,否則新建
@type/name // 只引用,找不到會報錯
// 實務上建議一律寫 + 號,避免定義順序帶來的意外
命名空間(xmlns)必須寫在最外層標籤上:
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
xmlns:settings="https://schemas.android.com/apk/res/com.android.email"
新建工程後,AndroidManifest.xml 默認引用的是 @style/AppTheme:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
往上追,它在 support v7 包的 res/values/themes.xml 中:
<style name="Theme.AppCompat.Light.DarkActionBar"
parent="Base.Theme.AppCompat.Light.DarkActionBar" />
再往上是 themes_base.xml:
<style name="Platform.AppCompat.Light" parent="android:Theme.Light">
<item name="android:windowNoTitle">true</item>
......
</style>
終點是 framework/base 下的 themes.xml:
<!-- 淺色背景配深色文字的主題 -->
<style name="Theme.Light">
<item name="isLightTheme">true</item>
<item name="windowBackground">@drawable/screen_background_selector_light</item>
......
</style>
<!-- 所有主題的開山鼻祖,API 10 及以下的預設主題 -->
<style name="Theme">
...... <!-- 文字樣式、按鈕樣式、列表屬性、窗體屬性、對話框屬性、
Toast、Panel、滾動條、Widget styles、Preference styles、
Action bar styles、SearchView 屬性 …… -->
</style>
這個 Theme 有四百多個 item,幾乎覆蓋了整個應用的文字、按鈕、列表、窗體、對話框默認樣式。自訂主題時,直接翻這個檔案往往比查 API 更方便——因為它既有值又有註釋。Theme.Light、Theme.NoTitleBar、Theme.NoTitleBar.Fullscreen 等常用擴展都在同一個檔裡,引用時前面加 android: 即可。style、attr 的組織方式也大致相同。
Theme 的設置方式有兩種:
<application> 或 <activity> 節點上設置 android:theme。setTheme(),且必須在 setContentView() 之前。為什麼必須在 setContentView 之前?我們沿著呼叫鏈走一遍。Activity 的 setContentView 最終走到 PhoneWindow:
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor(); // 每個 Activity 第一次進來必走
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
......
}
private void installDecor() {
if (mDecor == null) {
mDecor = generateDecor(); // 本質是一個 FrameLayout
......
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor); // 生成布局的父容器
mDecor.makeOptionalFitsSystemWindows();
......
}
}
關鍵在 generateLayout():
protected ViewGroup generateLayout(DecorView decor) {
// 取得當前主題 —— 重點就在這裡
TypedArray a = getWindowStyle();
// 解析一大堆主題屬性
mIsFloating = a.getBoolean(R.styleable.Window_windowIsFloating, false);
if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
requestFeature(FEATURE_NO_TITLE);
} else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
requestFeature(FEATURE_ACTION_BAR);
}
if (a.getBoolean(R.styleable.Window_windowFullscreen, false)) {
setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
}
// 依主題與 feature 挑選匹配的 decor 布局
int layoutResource;
int features = getLocalFeatures();
if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
layoutResource = R.layout.screen_swipe_dismiss;
} else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
R.attr.dialogTitleIconsDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = R.layout.screen_title_icons;
}
removeFeature(FEATURE_ACTION_BAR);
}
......
View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
mContentRoot = (ViewGroup) in;
ViewGroup contentParent = (ViewGroup) findViewById(ID_ANDROID_CONTENT);
......
return contentParent;
}
也就是說:Theme 屬性會在 generateLayout 階段被讀取,並決定選用哪一份 decor 布局、開啟哪些 feature。如果你在 setContentView 之後才 setTheme,主題已經被讀取並落地成視圖結構了,再改自然沒有效果。
繼續往上看 getWindowStyle():
public final TypedArray getWindowStyle() {
synchronized (this) {
if (mWindowStyle == null) {
mWindowStyle = mContext.obtainStyledAttributes(
com.android.internal.R.styleable.Window);
}
return mWindowStyle;
}
}
// Context
public final TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
return getTheme().obtainStyledAttributes(attrs);
}
Context.getTheme() 是抽象方法,Activity 的實現類是 ContextThemeWrapper:
@Override
public Resources.Theme getTheme() {
// 已設置過 Theme 就直接返回
if (mTheme != null) {
return mTheme;
}
// 否則依 targetSdkVersion 選一個默認主題
mThemeResource = Resources.selectDefaultTheme(
mThemeResource, getApplicationInfo().targetSdkVersion);
initializeTheme();
return mTheme;
}
@Override
public void setTheme(int resid) {
if (mThemeResource != resid) {
mThemeResource = resid;
initializeTheme();
}
}
默認主題的挑選邏輯在 Resources 中,按 targetSdkVersion 分檔:
public static int selectDefaultTheme(int curTheme, int targetSdkVersion) {
return selectSystemTheme(curTheme, targetSdkVersion,
com.android.internal.R.style.Theme, // API 11 以下
com.android.internal.R.style.Theme_Holo, // API 11 ~ 14
com.android.internal.R.style.Theme_DeviceDefault, // API 14 之後(深色)
com.android.internal.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}
public static int selectSystemTheme(int curTheme, int targetSdkVersion,
int orig, int holo, int dark, int deviceDefault) {
if (curTheme != 0) return curTheme;
if (targetSdkVersion < Build.VERSION_CODES.HONEYCOMB) return orig;
if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) return holo;
if (targetSdkVersion < Build.VERSION_CODES.CUR_DEVELOPMENT) return dark;
return deviceDefault;
}
這就解釋了為什麼不同 targetSdkVersion 的工程,默認主題長得不一樣。
而 AndroidManifest 中配置的主題,是在 ActivityThread 的 performLaunchActivity() 裡被讀出來並呼叫 activity.setTheme() 生效的——這發生在 Activity 啟動階段,早於你的代碼執行。
最後看真正幹活的 initializeTheme():
private void initializeTheme() {
final boolean first = mTheme == null;
if (first) {
mTheme = getResources().newTheme();
Resources.Theme theme = getBaseContext().getTheme();
if (theme != null) {
mTheme.setTo(theme);
}
}
onApplyThemeResource(mTheme, mThemeResource, first);
}
@Override
protected void onApplyThemeResource(Resources.Theme theme, int resid, boolean first) {
theme.applyStyle(resid, true);
}
// Resources.Theme
public void applyStyle(int resId, boolean force) {
AssetManager.applyThemeStyle(mTheme, resId, force);
mThemeResId = resId;
mKey.append(resId, force);
}
force = true 意味著主題中的屬性值會覆蓋已有值。至此,一個 Theme 就完成了「被選擇 → 被解析 → 被應用」的全過程。
回到最開始的 com.android.internal.R.styleable.Window,它在 framework 的 attrs.xml 中:
<!-- 描述一個 Window 主題的屬性集合 -->
<declare-styleable name="Window">
......
</declare-styleable>
<!-- 構成完整主題的標準屬性 -->
<declare-styleable name="Theme">
......
</declare-styleable>
這裡有個有意思的細節:這些 declare-styleable 中的屬性沒有聲明 format 字段。在 Android 中,自訂屬性若無 format,意味著該屬性已經定義過,這裡只是別名轉引。真正的定義在 Theme 這個 styleable 中,而 themes.xml 裡的 <style name="Theme"> 就是對這批屬性的賦值:
<style name="Theme">
<item name="isLightTheme">false</item>
<item name="colorForeground">@color/bright_foreground_dark</item>
<item name="colorForegroundInverse">@color/bright_foreground_dark_inverse</item>
......
</style>
看到這裡應該會有一種「似曾相識」的感覺——系統定製主題的方式,和我們在 App 裡自訂 attr + style 的做法完全一樣。
如果做過固件開發,可能會需要替換或新增系統資源。先認識幾個常見產物的來源:
修改與編譯的基本流程:改代碼 → 在對應目錄 mm 單獨編譯 → 把產物 push 到設備的 system 目錄 → 重啟驗證。
幾個實踐中的坑:mm 之前最好先清理 out/obj 下的中間產物,資源變更時尤其容易出問題;如果新增系統 API、修改 @hide API 或改動 public.xml,記得先執行 make update-api 同步 current.txt,再重新 make。
如果只想在 App 中使用 framework 的 hide 資源,又不想用反射、也不想依賴源碼編譯,可以自行編一個「無 hide 限制」的 jar 引入工程。注意要以 provided 方式引入(只編譯不打包),並保證依賴順序正確,否則還是會命中 SDK 裡的默認版本。
把整條鏈路串起來看:Theme 本質是 Style,Style 本質是一組 attr 的賦值集合,而系統早已預定義了海量 attr 供我們按規則取用。至於加載流程,則是 Context(透過 ContextThemeWrapper 決定用哪個 Theme)、Window(讀取 Theme 屬性並挑選 decor 布局與 feature)與 Resources/AssetManager(完成屬性解析與賦值)三者協同的結果。
理解了這層結構,再遇到詭異的顯示問題,第一反應應該是「去查是哪個屬性、哪個 parent、哪個版本分支」,而不是四處搜尋複製貼上。
Android 入門:簡單提示框與 Toast 閃現提示
需求說明在 Android 入門階段,提示框與 Toast 是很常用的互動元件。本文示範如何建立一個公用類別,讓多個頁面都能快速呼叫提示訊息,避免重複撰寫相同邏輯。建立公
Android 顏色資源使用完全指南
前言在 Android 開發中,顏色資源可分為兩種:一種是自行定義的顏色,另一種是使用系統內建的顏色。自訂顏色Android 的顏色值由透明度 alpha 與 RGB(紅
打造會縮放的 ImageView(下):拖動、雙擊變倍與 ViewPager 事件衝突
上一篇已經做出自由縮放並簡介了 Matrix,本篇把這個 ImageView 補完:加入放大後的拖動、雙擊切換倍率,最後處理與 ViewPager 的事件衝突。 一、放大
實時監聽手機旋轉角度,判斷橫豎屏佈局的加載時機
場景是這樣的 近期做橫豎屏切換時遇到一個尷尬:佈局的切換由操作系統感知,開發者無法直接得知 Activity 究竟在哪一刻加載了橫屏佈局、哪一那一刻加載了豎屏佈局。既然拿