Android 中為自定義 View 的屬性設置默認樣式

我們自定義控件的時候,最常見的需要重寫構造函數是 public View(Context context) {}public View(Context context, @Nullable AttributeSet attrs) {}, 因為第一個是在 Java 代碼中創建 View 時會調用,第二是在 XML 布局文件中引用 View 時,會被調用。這兩個構造函數都是系統會調用的方法。但是,還剩兩個構造函數`` public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {}public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {}`, 是需要我們自行調用的,系統并不會調用,當我們需要為自定義 View 設置默認的屬性的時候,就需要用到了。

這是一段典型的一段自定義 View 的構造函數。

public class AttrTestTextView extends TextView {
    public AttrTestTextView(Context context) {
        super(context);
    }

    public AttrTestTextView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.defaultStyleAttr);
    }

    public AttrTestTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, R.style.DefaultStyleRes);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public AttrTestTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AttrTestTextView,
                defStyleAttr, defStyleRes);

        ...

        typedArray.recycle();
    }
}

可以看出來,屬性的獲取主要由 context.obtainStyledAttributes 決定,而最后兩個參數defStyleAttrdefStyleRes決定了最終默認的屬性樣式是怎么的。

為了弄清楚默認樣式的運作規律,我們先為這個自定義 View 創建 5 個自定義屬性,和一個單獨的屬性,attrs.xml 文件如下:

<resources>
    <declare-styleable name="AttrTestTextView">
        <attr name="firstAttr" format="string" />
        <attr name="secondAttr" format="string" />
        <attr name="thirdAttr" format="string" />
        <attr name="fourthAttr" format="string" />
        <attr name="fifthAttr" format="string" />
    </declare-styleable>

    <attr name="defaultStyleAttr" format="reference" />
</resources

設置 5 個屬性的原因是 Android 的 View 屬性覆蓋的優先級有 5 處,分別是:

  1. 布局文件中的直接指定的屬性
  2. 布局文件中的 style 中指定的屬性
  3. 我們自己定義的 Style
  4. Theme 中直接指定的 Style 引用
  5. Theme 中直接指定的屬性

他們之間的覆蓋的優先級是:

1 > 2 > 3 / 4 > 5

為了驗證我們的結論,首先在Application 或 Activity 的 Theme 中直接設置這5個屬性,并且為上方定義的 defaultStyleAttr 屬性設置一個style的引用,值為下方定義的 @style/DefaultStyleInAppTheme, 而這個屬性將作為自定義View構造函數中的第三個值,即該自定義 View 默認的 style。DefaultStyleRes 則作為自定義 View 的構造函數中的第四個參數,而 LayoutStyle 則在布局中直接引用, styles.xml 文件如下:

<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="firstAttr">firstAttr from theme attr</item>
        <item name="secondAttr">secondAttr from theme attr</item>
        <item name="thirdAttr">thirdAttr from theme attr</item>
        <item name="fourthAttr">fourthAttr from theme attr</item>
        <item name="fifthAttr">fifthAttr from theme attr</item>

        <item name="defaultStyleAttr">@style/DefaultStyleInAppTheme</item>
    </style>

    <style name="DefaultStyleInAppTheme">
        <item name="firstAttr">firstAttr from theme style</item>
        <item name="secondAttr">secondAttr from theme style</item>
        <item name="thirdAttr">thirdAttr from theme style</item>
    </style>

    <style name="DefaultStyleRes">
        <item name="firstAttr">firstAttr from style res</item>
        <item name="secondAttr">secondAttr from style res</item>
        <item name="thirdAttr">thirdAttr from style res</item>
        <item name="fourthAttr">fourthAttr from style res</item>
    </style>

    <style name="LayoutStyle">
        <item name="firstAttr">firstAttr from layout style</item>
        <item name="secondAttr">secondAttr from layout style</item>
    </style>

</resources

然后我們自定義一個 TextView, 分別獲取這 5 個屬性的值,并且顯示出來。

public class AttrTestTextView extends TextView {
    public AttrTestTextView(Context context) {
        super(context);
    }

    public AttrTestTextView(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.defaultStyleAttr);
    }

    public AttrTestTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, R.style.DefaultStyleRes);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public AttrTestTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AttrTestTextView,
                defStyleAttr, defStyleRes);

        StringBuilder sb = new StringBuilder();
        sb.append(typedArray.getString(R.styleable.AttrTestTextView_firstAttr)).append("\n");
        sb.append(typedArray.getString(R.styleable.AttrTestTextView_secondAttr)).append("\n");
        sb.append(typedArray.getString(R.styleable.AttrTestTextView_thirdAttr)).append("\n");
        sb.append(typedArray.getString(R.styleable.AttrTestTextView_fourthAttr)).append("\n");
        sb.append(typedArray.getString(R.styleable.AttrTestTextView_fifthAttr));

        setText(sb);

        typedArray.recycle();
    }
}

我們知道,屬性的獲取最終是根據 obtainStyledAttributes() 方法獲得,他的最后兩個參數也就是構造行數的最后兩個參數,這兩個參數都是設置自定義 View 的默認樣式,那么,他們作用的優先級是怎樣的?

* @param defStyleRes A resource identifier of a style resource that
*        supplies default values for the view, used only if
*        defStyleAttr is 0 or can not be found in the theme. Can be 0
*        to not look for defaults.

根據 API 文檔的可以看出,當 defStyleAttr 參數被設置為 0, 或者在 Application 和 Activity 的 Theme 中找不到 defStyleAttr 屬性的賦值(例如 styles.xml 中的 <item name="defaultStyleAttr">@style/DefaultStyleInAppTheme</item> 這行代碼被刪除),那么,這個 View 的默認樣式就是 defStyleRes 參數所引用的屬性樣式。可以看出這兩個參數是沖突的,而且沖突級別是整個 style, 即 defStyleAttr 參數的 style 能找到情況下就忽略了整個 defStyleRes 的屬性集。

然后,在布局文件中添加自定義的 View,分別設置了直接的屬性,firstAttr 和 設置了 styles.xml 中定義的 style。

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <com.ryeeeeee.attrtest.AttrTestTextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:firstAttr="firstAttr from layout attr"
            style="@style/LayoutStyle"/>

</RelativeLayout>

運行結果如下圖,可以看到 defStyleRes 所引用的 style 中的屬性完全被忽略了,因為 styles.xml 中能找到 defStyleAttr 這個屬性的賦值:

WechatIMG1.png

現在將 styles.xml 中能找到 defStyleAttr 這個屬性的賦值刪除,或者將 defStyleAttr 參數使用 0 賦值, 運行結果如下,可以看到 defStyleRes 所引用的style 才顯示出來:

WechatIMG2.png

實驗結果證明,屬性層級的覆蓋優先級是 1 > 2 > 3 / 4 > 5,和上方結論一致。需要注意的是,在 style 層級的優先級 defStyleAttr 參數所引用的 style 的優先級是高于 defStyleRes 的。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內容