QMUI源码分析之QMUIRoundButton

核心类

  • QMUIRoundButton:继承自QMUIAlphaButtonAppCompatButton, 默认样式为 QMUI.RoundButton
  • QMUIRoundButtonDrawable: QMUIRoundButton 的背景生成类
  • QMUIViewHelper: 辅助类,用于设置背景。

QMUIRoundButton

QMUIRoundButton 的每一个构造函数中都调用了 init(), 通过查看 init()发现核心是获取一个 Drawable 对象,并将其作为背景赋值给自身.
- QMUIRoundButtonDrawable.fromAttributeSet() 负责生成Drawable 对象
- QMUIViewHelper.setBackgroundKeepingPadding() 负责调用 view.setBackground(drawable).

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        // 获取背景
        QMUIRoundButtonDrawable bg = QMUIRoundButtonDrawable.fromAttributeSet(context, attrs, defStyleAttr);
        // 设置背景
        QMUIViewHelper.setBackgroundKeepingPadding(this, bg);
        // 设置disable 时不改变透明度
        setChangeAlphaWhenDisable(false);
        // 设置press 时不改变透明度
        setChangeAlphaWhenPress(false);
    }

QMUIViewHelper

通过调用setBackgroundKeepingPadding() 来设置背景并保持原有的内边距

    /**
     * 设置默认边距与背景
     * @param view
     * @param drawable
     */
    public static void setBackgroundKeepingPadding(View view, Drawable drawable) {
        int[] padding = new int[]{view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom()};
        setBackground(view, drawable);
        view.setPadding(padding[0], padding[1], padding[2], padding[3]);
    }
    
    /**
     * 给View 设置背景 drawable
     * @param view
     * @param drawable
     */
    @SuppressWarnings("deprecation")
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static void setBackground(View view, Drawable drawable){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(drawable);
        } else {
            view.setBackgroundDrawable(drawable);
        }
    }

QMUIRoundButtonDrawable

QMUIRoundButtonDrawable 获取Drawable 对象

获取属性,并将属性赋值给一个QMUIRoundButtonDrawable对象且返回

    public static QMUIRoundButtonDrawable fromAttributeSet(Context context, AttributeSet attrs, int defStyleAttr) {
        // 通过TypedArray 对象获取在xml中定义的属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.QMUIRoundButton, defStyleAttr, 0);
        // 获取带状态的背景颜色
        ColorStateList colorBg = typedArray.getColorStateList(R.styleable.QMUIRoundButton_qmui_backgroundColor);
        // 获取带状态的边框颜色
        ColorStateList colorBorder = typedArray.getColorStateList(R.styleable.QMUIRoundButton_qmui_borderColor);
        // 边框宽度
        int borderWidth = typedArray.getDimensionPixelSize(R.styleable.QMUIRoundButton_qmui_borderWidth, 0);
        // 圆角是否是短边的一半 默认为false
        boolean isRadiusAdjustBounds = typedArray.getBoolean(R.styleable.QMUIRoundButton_qmui_isRadiusAdjustBounds, false);
        // 获取圆角值 默认为0
        int mRadius = typedArray.getDimensionPixelSize(R.styleable.QMUIRoundButton_qmui_radius, 0);
        int mRadiusTopLeft = typedArray.getDimensionPixelSize(R.styleable.QMUIRoundButton_qmui_radiusTopLeft, 0);
        int mRadiusTopRight = typedArray.getDimensionPixelSize(R.styleable.QMUIRoundButton_qmui_radiusTopRight, 0);
        int mRadiusBottomLeft = typedArray.getDimensionPixelSize(R.styleable.QMUIRoundButton_qmui_radiusBottomLeft, 0);
        int mRadiusBottomRight = typedArray.getDimensionPixelSize(R.styleable.QMUIRoundButton_qmui_radiusBottomRight, 0);
        // 记得回收
        typedArray.recycle();

        QMUIRoundButtonDrawable bg = new QMUIRoundButtonDrawable();
        // 设置背景颜色
        bg.setBgData(colorBg);
        // 设置边框颜色与宽度
        bg.setStrokeData(borderWidth, colorBorder);
        // 圆角带优先级为 单个圆角 > 四个圆角 > 圆角是否是短边的一半
        if (mRadiusTopLeft > 0 || mRadiusTopRight > 0 || mRadiusBottomLeft > 0 || mRadiusBottomRight > 0) {
            float[] radii = new float[]{
                    mRadiusTopLeft, mRadiusTopLeft,
                    mRadiusTopRight, mRadiusTopRight,
                    mRadiusBottomRight, mRadiusBottomRight,
                    mRadiusBottomLeft, mRadiusBottomLeft
            };
            bg.setCornerRadii(radii);
            isRadiusAdjustBounds = false;
        } else {
            bg.setCornerRadius(mRadius);
            if(mRadius > 0){
                isRadiusAdjustBounds = false;
            }
        }
        bg.setIsRadiusAdjustBounds(isRadiusAdjustBounds);
        return bg;
    }

设置背景与边框

通过以上步骤分解可以看出关键在于
1. 设置背景颜色
2. 设置边框颜色与宽度(以上两种要注意在android 5.0 以下需要手动工具状态设置对应的颜色)

只贴出了设置背景颜色的代码,设置边框颜色的代码类似


    private boolean hasNativeStateListAPI() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }
    
    public void setBgData(@Nullable ColorStateList colors) {
        // 版本 5.0以上 支持直接设置,5.0以下需要手动获取当前状态颜色再赋值
        if (hasNativeStateListAPI()) {
            super.setColor(colors);
        } else {
            mFillColors = colors;
            final int currentColor;
            if (colors == null) {
                currentColor = Color.TRANSPARENT;
            } else {
                currentColor = colors.getColorForState(getState(), 0);
            }
            setColor(currentColor);
        }
    }

onStateChange()

对于Android 5.0 以下需要特殊处理,当状态改变时判断是否需要重新绘制对应状态的UI

/**
 * @param stateSet
 * @return true 表示状态改变需要改变UI,将会重绘,false 表示相反
 */
@Override
protected boolean onStateChange(int[] stateSet) {
    boolean superRet = super.onStateChange(stateSet);
    if (mFillColors != null) {
        int color = mFillColors.getColorForState(stateSet, 0);
        setColor(color);
        superRet = true;
    }
    if (mStrokeColors != null) {
        int color = mStrokeColors.getColorForState(stateSet, 0);
        setStroke(mStrokeWidth, color);
        superRet = true;
    }
    return superRet;
}

QMUI提供的默认样式

<style name="QMUI.RoundButton" parent="@style/Button">
    <!--<item name="android:padding">0dp</item>--><!-- 不用 android:padding,而用各个方向分别指定 padding,方便子类覆盖 -->
    <item name="android:paddingLeft">0dp</item>
    <item name="android:paddingRight">0dp</item>
    <item name="android:paddingTop">0dp</item>
    <item name="android:paddingBottom">0dp</item>
    <!-- 默认圆角是短边的一半 -->
    <item name="qmui_isRadiusAdjustBounds">true</item>
    <!-- 默认背景颜色为透明的 -->
    <item name="qmui_backgroundColor">@color/qmui_s_transparent</item>
    <!-- 默认边框宽度为 1dp -->
    <item name="qmui_borderWidth">?attr/qmui_round_btn_border_width</item>
    <!-- 默认边框颜色 -->
    <item name="qmui_borderColor">?attr/qmui_round_btn_border_color</item>
    <!-- 默认文字颜色 -->
    <item name="android:textColor">?attr/qmui_round_btn_text_color</item>
</style>

总结

通过以上源码分析可以学习到的核心知识点有:

  1. 通过extends 的方式实现自定义View
  2. 通过 TypedArray 获取自定义属性值
  3. 通过自定义 Drawable 来指定圆角、边框颜色、边框粗细、背景色
  4. ColorStateList 的初次相识,其实质就是对应于 selector 标签中的各种 state_xxx参考链接
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,104评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,816评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,697评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,836评论 1 298
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,851评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,441评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,992评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,899评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,457评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,529评论 3 341
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,664评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,346评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,025评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,511评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,611评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,081评论 3 377
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,675评论 2 359

推荐阅读更多精彩内容