Android 中為自定義 View 的屬性設(shè)置默認(rèn)樣式

我們自定義控件的時(shí)候缸逃,最常見(jiàn)的需要重寫(xiě)構(gòu)造函數(shù)是 public View(Context context) {}public View(Context context, @Nullable AttributeSet attrs) {}, 因?yàn)榈谝粋€(gè)是在 Java 代碼中創(chuàng)建 View 時(shí)會(huì)調(diào)用耕突,第二是在 XML 布局文件中引用 View 時(shí),會(huì)被調(diào)用芹橡。這兩個(gè)構(gòu)造函數(shù)都是系統(tǒng)會(huì)調(diào)用的方法毒坛。但是,還剩兩個(gè)構(gòu)造函數(shù)`` public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {}public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {}`, 是需要我們自行調(diào)用的林说,系統(tǒng)并不會(huì)調(diào)用煎殷,當(dāng)我們需要為自定義 View 設(shè)置默認(rèn)的屬性的時(shí)候,就需要用到了腿箩。

這是一段典型的一段自定義 View 的構(gòu)造函數(shù)豪直。

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();
    }
}

可以看出來(lái),屬性的獲取主要由 context.obtainStyledAttributes 決定珠移,而最后兩個(gè)參數(shù)defStyleAttrdefStyleRes決定了最終默認(rèn)的屬性樣式是怎么的弓乙。

為了弄清楚默認(rèn)樣式的運(yùn)作規(guī)律末融,我們先為這個(gè)自定義 View 創(chuàng)建 5 個(gè)自定義屬性,和一個(gè)單獨(dú)的屬性暇韧,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

設(shè)置 5 個(gè)屬性的原因是 Android 的 View 屬性覆蓋的優(yōu)先級(jí)有 5 處勾习,分別是:

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

他們之間的覆蓋的優(yōu)先級(jí)是:

1 > 2 > 3 / 4 > 5

為了驗(yàn)證我們的結(jié)論,首先在Application 或 Activity 的 Theme 中直接設(shè)置這5個(gè)屬性懈玻,并且為上方定義的 defaultStyleAttr 屬性設(shè)置一個(gè)style的引用巧婶,值為下方定義的 @style/DefaultStyleInAppTheme, 而這個(gè)屬性將作為自定義View構(gòu)造函數(shù)中的第三個(gè)值,即該自定義 View 默認(rèn)的 style涂乌。DefaultStyleRes 則作為自定義 View 的構(gòu)造函數(shù)中的第四個(gè)參數(shù)艺栈,而 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

然后我們自定義一個(gè) TextView湾盒, 分別獲取這 5 個(gè)屬性的值湿右,并且顯示出來(lái)。

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();
    }
}

我們知道罚勾,屬性的獲取最終是根據(jù) obtainStyledAttributes() 方法獲得毅人,他的最后兩個(gè)參數(shù)也就是構(gòu)造行數(shù)的最后兩個(gè)參數(shù),這兩個(gè)參數(shù)都是設(shè)置自定義 View 的默認(rèn)樣式荧库,那么堰塌,他們作用的優(yōu)先級(jí)是怎樣的赵刑?

* @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.

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

然后科乎,在布局文件中添加自定義的 View壁畸,分別設(shè)置了直接的屬性,firstAttr 和 設(shè)置了 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>

運(yùn)行結(jié)果如下圖捏萍,可以看到 defStyleRes 所引用的 style 中的屬性完全被忽略了,因?yàn)?styles.xml 中能找到 defStyleAttr 這個(gè)屬性的賦值:

WechatIMG1.png

現(xiàn)在將 styles.xml 中能找到 defStyleAttr 這個(gè)屬性的賦值刪除空闲,或者將 defStyleAttr 參數(shù)使用 0 賦值, 運(yùn)行結(jié)果如下令杈,可以看到 defStyleRes 所引用的style 才顯示出來(lái):

WechatIMG2.png

實(shí)驗(yàn)結(jié)果證明,屬性層級(jí)的覆蓋優(yōu)先級(jí)是 1 > 2 > 3 / 4 > 5碴倾,和上方結(jié)論一致逗噩。需要注意的是掉丽,在 style 層級(jí)的優(yōu)先級(jí) defStyleAttr 參數(shù)所引用的 style 的優(yōu)先級(jí)是高于 defStyleRes 的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末异雁,一起剝皮案震驚了整個(gè)濱河市捶障,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌纲刀,老刑警劉巖残邀,帶你破解...
    沈念sama閱讀 219,270評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異柑蛇,居然都是意外死亡芥挣,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)耻台,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)空免,“玉大人,你說(shuō)我怎么就攤上這事盆耽√Q猓” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,630評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵摄杂,是天一觀的道長(zhǎng)坝咐。 經(jīng)常有香客問(wèn)我,道長(zhǎng)析恢,這世上最難降的妖魔是什么墨坚? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,906評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮映挂,結(jié)果婚禮上泽篮,老公的妹妹穿的比我還像新娘。我一直安慰自己柑船,他們只是感情好帽撑,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,928評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著鞍时,像睡著了一般亏拉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上逆巍,一...
    開(kāi)封第一講書(shū)人閱讀 51,718評(píng)論 1 305
  • 那天及塘,我揣著相機(jī)與錄音,去河邊找鬼蒸苇。 笑死磷蛹,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的溪烤。 我是一名探鬼主播味咳,決...
    沈念sama閱讀 40,442評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼庇勃,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了槽驶?” 一聲冷哼從身側(cè)響起责嚷,我...
    開(kāi)封第一講書(shū)人閱讀 39,345評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎掂铐,沒(méi)想到半個(gè)月后罕拂,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,802評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡全陨,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,984評(píng)論 3 337
  • 正文 我和宋清朗相戀三年爆班,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辱姨。...
    茶點(diǎn)故事閱讀 40,117評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡柿菩,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出雨涛,到底是詐尸還是另有隱情枢舶,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評(píng)論 5 346
  • 正文 年R本政府宣布替久,位于F島的核電站凉泄,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蚯根。R本人自食惡果不足惜后众,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,462評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望稼锅。 院中可真熱鬧吼具,春花似錦、人聲如沸矩距。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,011評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)锥债。三九已至,卻和暖如春痊臭,著一層夾襖步出監(jiān)牢的瞬間哮肚,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,139評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工广匙, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留允趟,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,377評(píng)論 3 373
  • 正文 我出身青樓鸦致,卻偏偏與公主長(zhǎng)得像潮剪,于是被迫代替她去往敵國(guó)和親涣楷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,060評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容