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阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容