編輯:關於 Android 程式設計
寫 XML 版面時我們很少替 TextView 指定 style,但它就是有字級、有顏色、有邊距。這些預設值到底從哪冒出來的?答案藏在 Theme 與 Style 的三層關係裡。
public TextView(Context context) {
this(context, null);
}
public TextView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}
@SuppressWarnings("deprecation")
public TextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// ...
TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
// ...
}
Android 提供的控制項幾乎都有這三個建構子,用途各不相同:
new TextView(this) 使用。我們通常不指定 style,所以走第二個建構子。而它做的事就是把 com.android.internal.R.attr.textViewStyle 當成 defStyle 傳給第三個建構子:
public TextView(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}
這個 textViewStyle 只是一個 ID 參照,定義在系統的 attr.xml:
<!-- Default TextView style. -->
<attr name="textViewStyle" format="reference" />
問題來了:它只是一個「指標」,本身沒有值。那值在哪?
預設 style 的值是在 Activity 的 Theme 中指定的:
<style name="Theme">
<item name="textViewStyle">@android:style/Widget.TextView</item>
</style>
Theme 是所有主題的基類,所以無論你的 Activity 套用哪個 theme,都能沿著繼承鏈找到 textViewStyle。這也解釋了一個常見現象:換 theme 會讓控制項外觀全變,因為所有預設 style 指標都指向不同目標。
而 @android:style/Widget.TextView 指向系統的 style 資源:
<style name="Widget.TextView">
<item name="android:textAppearance">?android:attr/textAppearanceSmall</item>
<item name="android:textSelectHandleLeft">?android:attr/textSelectHandleLeft</item>
<item name="android:textSelectHandleRight">?android:attr/textSelectHandleRight</item>
<item name="android:textSelectHandle">?android:attr/textSelectHandle</item>
</style>
注意 ?android:attr/ 和 @android:style/ 的差別:? 表示「從目前主題中取值」,@ 表示「直接參照這個資源」。所以 textAppearanceSmall 又會依主題不同而變化,形成一層層的間接參照。
TypedArray a = context.obtainStyledAttributes(
attrs, com.android.internal.R.styleable.TextView, defStyle, 0);
這行程式可以理解為:用 attrs 和 defStyle 兩份來源,去解析 R.styleable.TextView 中宣告的那批屬性。三個來源概念的分工是:
解析的優先順序是「XML 直接寫的 > style > 主題預設」,這就是為什麼你在 XML 寫 android:textSize="30sp" 能蓋掉主題的字級。
最後再用 TypedArray 的 getter 把值取出來:
mThumbDrawable = a.getDrawable(R.styleable.Switch_thumb);
mTrackDrawable = a.getDrawable(R.styleable.Switch_track);
mTextOn = a.getText(R.styleable.Switch_textOn);
mTextOff = a.getText(R.styleable.Switch_textOff);
defStyle 參數指定的預設 style。textViewStyle 這類 item 指定的。
一個 App 兩個圖示:模擬 QQ 郵箱的桌面捷徑方案
需求聽起來有點無厘頭:桌面上要有兩個圖示,看起來像兩個獨立 App,點不同圖示進入不同功能——就像 QQ 郵箱同時提供「郵箱」與「日曆」兩個入口那樣。本文記錄當時的實作思
Cocos2d-JS 3.x 與 WebStorm 開發環境搭建
本文整理如何使用 WebStorm 建立與除錯 Cocos2d-JS 專案。內容涵蓋環境準備、專案建立、執行方式、語法補全設定,以及 JavaScript 與 C++ 互
性能優化視圖篇:ListView 自適應引發的嚴重性能隱患
ListView 是 Android 中使用頻率僅次於三大基礎布局的元老級控件。儘管因擴展性等原因備受爭議,也有 RecyclerView 作為替代方案,但它至今仍廣泛存
Android Studio 下的 NDK JNI 開發完整入門
早些年用 Eclipse 搭配 NDK 研究 JNI 時,總覺得設定與開發都相當繁瑣。近來改用 Android Studio 開發 JNI,整體體驗順暢許多,於是趁機把流