支持边框、圆角、渐变色、透明度的GradientButton

最近在项目中发现好多Button背景颜色相同,但圆角大小不等的Button,这样就得写一大堆的shape或者selector,不便于管理及后期维护,于是乎变想能不能写一个支持边框、圆角、渐变色、透明度的万用Button呢。为了能够兼容button自带的属性,当然继承自AppCompatButton是最好的,剩下的就需要考虑selector各状态在我们自定义Button中怎么获取与渲染了。最开始想到,自己draw?不过这样有点low,需要我们处理一大堆的状态,譬如:state_pressedstate_enabled...
那有没有更好的实现方式呢?我们把这些状态交由系统管理呢?在一顿寻找后,发现还真有呢,真是踏破铁鞋无觅处,得来全不费工夫--------GradientDrawable,没错就是它,一个Drawable的子类。我们看看它的描叙:

A Drawable with a color gradient for buttons, backgrounds, etc.

并且通过查看它提供的相应方法,它不仅能替我们管理好各种state,也支持边框绘制、圆角设置,渐变色当然更不用说了,看它的名字就知道啦。好了废话就不多说了,下面就是GradientButton的代码实现过程:

const val TOP_BOTTOM = 0
const val TR_BL = 1
const val RIGHT_LEFT = 2
const val BR_TL = 3
const val BOTTOM_TOP = 4
const val BL_TR = 5
const val LEFT_RIGHT = 6
const val TL_BR = 7

class GradientButton(context: Context, attrs: AttributeSet? = null) :
        AppCompatButton(context, attrs, android.R.attr.borderlessButtonStyle) {

    @IntDef(TOP_BOTTOM, TR_BL, RIGHT_LEFT, BR_TL, BOTTOM_TOP, BL_TR, LEFT_RIGHT, TL_BR)
    @kotlin.annotation.Retention(AnnotationRetention.SOURCE)
    annotation class Orientation

    private val radii by lazy { FloatArray(8) }

    private var mBackgroundDrawable: GradientButtonDrawable? = null

    private var mPaddingLeft = 0.0f
    private var mPaddingTop = 0.0f
    private var mPaddingRight = 0.0f
    private var mPaddingBottom = 0.0f

    private var mMinWidth = 0
    private var mMinHeight = 0

    init {
        val stateListDrawable = StateListDrawable()
        attrs?.also { it ->
            context.obtainStyledAttributes(it, R.styleable.GradientButton).apply {
                val borderColorStateList = getColorStateList(R.styleable.GradientButton_border_color)
                val borderWidth = getDimension(R.styleable.GradientButton_border_width, 0.0f)
                val isRadiusAdjustBounds = getBoolean(R.styleable.GradientButton_is_radius_adjust_bounds, false)
                val radius = getDimension(R.styleable.GradientButton_all_radius, 0.0f)
                val topLeftRadius = getDimension(R.styleable.GradientButton_top_left_radius, 0.0f)
                val topRightRadius = getDimension(R.styleable.GradientButton_top_right_radius, 0.0f)
                val bottomLeftRadius = getDimension(R.styleable.GradientButton_bottom_left_radius, 0.0f)
                val bottomRightRadius = getDimension(R.styleable.GradientButton_bottom_right_radius, 0.0f)
                val backgroundColorStateList = getColorStateList(R.styleable.GradientButton_background_color)
                val orientation = getInt(R.styleable.GradientButton_orientation, LEFT_RIGHT)
                val startBackgroundColorStateList =
                        getColorStateList(R.styleable.GradientButton_start_background_color)
                val centerBackgroundColorStateList =
                        getColorStateList(R.styleable.GradientButton_center_background_color)
                val endBackgroundColorStateList = getColorStateList(R.styleable.GradientButton_end_background_color)
                val backgroundAlpha = getFraction(R.styleable.GradientButton_background_alpha, 1, 1, 0.0f)
                val padding = getDimension(R.styleable.GradientButton_padding, -1.0f)
                mPaddingLeft = (if (padding != -1.0f) {
                    padding
                } else {
                    getDimension(R.styleable.GradientButton_padding_left, mPaddingLeft)
                })
                mPaddingTop = (if (padding != -1.0f) {
                    padding
                } else {
                    getDimension(R.styleable.GradientButton_padding_top, mPaddingTop)
                })
                mPaddingRight  = (if (padding != -1.0f) {
                    padding
                } else {
                    getDimension(R.styleable.GradientButton_padding_right, mPaddingRight)
                })
                mPaddingBottom  = (if (padding != -1.0f) {
                    padding
                } else {
                    getDimension(R.styleable.GradientButton_padding_bottom, mPaddingBottom)
                })
                mMinWidth = getDimensionPixelSize(R.styleable.GradientButton_min_width, 0)
                mMinHeight = getDimensionPixelSize(R.styleable.GradientButton_min_height, 0)
                mBackgroundDrawable = createBackgroundDrawable(getOrientation(orientation))
                if (borderWidth > 0.0f || backgroundColorStateList != null || (startBackgroundColorStateList != null && endBackgroundColorStateList != null)) {
                    setTopLeftRadius(topLeftRadius)
                    setTopRightRadius(topRightRadius)
                    setBottomLeftRadius(bottomLeftRadius)
                    setBottomRightRadius(bottomRightRadius)
                    setRadius(radius)
                    setBorder(borderWidth, borderColorStateList)
                    setBackgroundColorStateList(backgroundColorStateList)
                    setGradientBackgroundColorStateList(
                            startBackgroundColorStateList,
                            centerBackgroundColorStateList,
                            endBackgroundColorStateList
                    )
                    setBackgroundAlpha(backgroundAlpha)
                    mBackgroundDrawable?.setRadius(isRadiusAdjustBounds, radii)
                }
                recycle()
            }
        } ?: also {
            mBackgroundDrawable = createBackgroundDrawable(getOrientation(LEFT_RIGHT))
        }
        mBackgroundDrawable?.also {
            stateListDrawable.addState(it.state, mBackgroundDrawable)
            setGradientDrawable(stateListDrawable)
        }
        setPadding(mPaddingLeft.toInt(), mPaddingTop.toInt(), mPaddingRight.toInt(), mPaddingBottom.toInt())
        minWidth = mMinWidth
        minimumWidth = mMinWidth
        minHeight = mMinHeight
        minimumHeight = mMinHeight
    }

    private fun setGradientDrawable(stateListDrawable: StateListDrawable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            background = stateListDrawable
        } else {
            setBackgroundDrawable(stateListDrawable)
        }
    }

    /**
     * 设置渐变色方向
     */
    fun setOrientation(@Orientation orientation: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mBackgroundDrawable?.orientation = getOrientation(orientation)
        }
    }

    fun setBackgroundAlpha(@FloatRange(from = 0.0, to = MAX_VALUE) alpha: Float) {
        mBackgroundDrawable?.alpha = ((1.0f - alpha) * 255).toInt()
    }

    /**
     * 渐变色设置
     */
    fun setGradientBackgroundColorStateList(
            startBackgroundColorStateList: ColorStateList?,
            centerBackgroundColorStateList: ColorStateList? = null,
            endBackgroundColorStateList: ColorStateList?
    ) {
        mBackgroundDrawable?.setGradientBackgroundColorStateList(
                startBackgroundColorStateList,
                centerBackgroundColorStateList,
                endBackgroundColorStateList
        )
    }

    fun setBackgroundColorStateList(backgroundColorStateList: ColorStateList?) {
        mBackgroundDrawable?.setBackgroundColorStateList(backgroundColorStateList)
    }

    fun setBackgroundColorRes(@ColorRes backgroundColor: Int) {
        setBackgroundColorRes(backgroundColor, backgroundColor, backgroundColor)
    }

    fun setBackgroundColorRes(@ColorRes startBackgroundColor: Int, @ColorRes centerBackgroundColor: Int?, @ColorRes endBackgroundColor: Int) {
        val centerBackgroundColorStateList = centerBackgroundColor?.let {
            ColorStateList(arrayOf(intArrayOf(android.R.attr.state_enabled)), intArrayOf(context.resources.getColor(it)))
        }
        mBackgroundDrawable?.setGradientBackgroundColorStateList(ColorStateList(arrayOf(intArrayOf(android.R.attr.state_enabled)),
                intArrayOf(context.resources.getColor(startBackgroundColor))),
                centerBackgroundColorStateList,
                ColorStateList(arrayOf(intArrayOf(android.R.attr.state_enabled)),
                        intArrayOf(context.resources.getColor(endBackgroundColor))))
    }

    private fun getOrientation(@Orientation orientation: Int): GradientDrawable.Orientation {
        return when (orientation) {
            TOP_BOTTOM -> GradientDrawable.Orientation.TOP_BOTTOM
            TR_BL -> GradientDrawable.Orientation.TR_BL
            RIGHT_LEFT -> GradientDrawable.Orientation.RIGHT_LEFT
            BR_TL -> GradientDrawable.Orientation.BR_TL
            BOTTOM_TOP -> GradientDrawable.Orientation.BOTTOM_TOP
            BL_TR -> GradientDrawable.Orientation.BL_TR
            TL_BR -> GradientDrawable.Orientation.TL_BR
            else -> GradientDrawable.Orientation.LEFT_RIGHT
        }
    }

    private fun createBackgroundDrawable(orientation: GradientDrawable.Orientation) =
            GradientButtonDrawable(orientation, null)

    fun setBorder(@FloatRange(from = 0.0, to = MAX_VALUE) borderWidth: Float, borderColorStateList: ColorStateList?) {
        mBackgroundDrawable?.setBorder(borderWidth, borderColorStateList)
    }

    fun setBorder(@FloatRange(from = 0.0, to = MAX_VALUE) borderWidth: Float, @ColorRes borderColorRes: Int){
        setBorder(borderWidth, ColorStateList(arrayOf(intArrayOf(android.R.attr.state_enabled)),
                intArrayOf(context.resources.getColor(borderColorRes))))
    }

    /**
     * 设置圆角自适应最小边
     */
    fun setRadiusAdjustBounds(isRadiusAdjustBounds: Boolean) {
        mBackgroundDrawable?.setRadius(isRadiusAdjustBounds, null)
    }

    fun setRadius(@FloatRange(from = 0.0, to = MAX_VALUE) radius: Float) {
        if (radius > 0.0f) {
            for (index in radii.indices) {
                radii[index] = radius
            }
            mBackgroundDrawable?.setRadius(radius = radii)
        }
    }

    fun setTopLeftRadius(@FloatRange(from = 0.0, to = MAX_VALUE) topLeftRadius: Float) {
        if (topLeftRadius > 0.0f) {
            radii[0] = topLeftRadius
            radii[1] = topLeftRadius
            mBackgroundDrawable?.setRadius(radius = radii)
        }
    }

    fun setTopRightRadius(@FloatRange(from = 0.0, to = MAX_VALUE) topRightRadius: Float) {
        if (topRightRadius > 0.0f) {
            radii[2] = topRightRadius
            radii[3] = topRightRadius
            mBackgroundDrawable?.setRadius(radius = radii)
        }
    }

    fun setBottomLeftRadius(@FloatRange(from = 0.0, to = MAX_VALUE) bottomLeftRadius: Float) {
        if (bottomLeftRadius > 0.0f) {
            radii[6] = bottomLeftRadius
            radii[7] = bottomLeftRadius
            mBackgroundDrawable?.setRadius(radius = radii)
        }
    }

    fun setBottomRightRadius(@FloatRange(from = 0.0, to = MAX_VALUE) bottomRightRadius: Float) {
        if (bottomRightRadius > 0.0f) {
            radii[4] = bottomRightRadius
            radii[5] = bottomRightRadius
            mBackgroundDrawable?.setRadius(radius = radii)
        }
    }
}
internal class GradientButtonDrawable(orientation: Orientation = Orientation.LEFT_RIGHT, @ColorInt colors: IntArray?) : GradientDrawable(orientation, colors) {

    private var mBackgroundColorStateList: ColorStateList? = null
    private var mStartBackgroundColorStateList: ColorStateList? = null
    private var mCenterBackgroundColorStateList: ColorStateList? = null
    private var mEndBackgroundColorStateList: ColorStateList? = null
    private var mBorderColorStateList: ColorStateList? = null
    private var mBorderWidth = 0.0f
    private var mIsRadiusAdjustBounds = false

    internal fun setBackgroundColorStateList(backgroundColorStateList: ColorStateList?) {
        mBackgroundColorStateList = backgroundColorStateList
        mStartBackgroundColorStateList = null
        mCenterBackgroundColorStateList = null
        mEndBackgroundColorStateList = null
        setBackgroundColor()
    }

    internal fun setGradientBackgroundColorStateList(startBackgroundColorStateList: ColorStateList?, centerBackgroundColorStateList: ColorStateList?, endBackgroundColorStateList: ColorStateList?) {
        mBackgroundColorStateList = null
        mStartBackgroundColorStateList = startBackgroundColorStateList
        mCenterBackgroundColorStateList = centerBackgroundColorStateList
        mEndBackgroundColorStateList = endBackgroundColorStateList
        setBackgroundColor()
    }

    internal fun setBorder(@FloatRange(from = 0.0, to = MAX_VALUE) borderWidth: Float = 0.0f, borderColorStateList: ColorStateList?) {
        mBorderWidth = borderWidth
        mBorderColorStateList = borderColorStateList
        setBorderColor()
    }

    internal fun setRadius(radiusAdjustBounds: Boolean = false, radius: FloatArray?) {
        mIsRadiusAdjustBounds = radiusAdjustBounds
        if (!mIsRadiusAdjustBounds) {
            cornerRadii = radius
        }
    }

    private fun getColorForState(colorStateList: ColorStateList?): Int {
        return colorStateList?.getColorForState(state, 0) ?: 0
    }

    private fun setBackgroundColor() {
        mBackgroundColorStateList?.also {
            if (hasNativeStateListAPI()) {
                color = mBackgroundColorStateList
            } else {
                setColor(getColorForState(mBackgroundColorStateList))
            }
        } ?: also {
            if (mStartBackgroundColorStateList != null && mEndBackgroundColorStateList != null) {
                val colors = IntArray(mCenterBackgroundColorStateList?.let { 3 } ?: let { 2 })
                colors[0] = getColorForState(mStartBackgroundColorStateList)
                mCenterBackgroundColorStateList?.also {
                    colors[1] = getColorForState(mCenterBackgroundColorStateList)
                    colors[2] = getColorForState(mEndBackgroundColorStateList)
                } ?: also {
                    colors[1] = getColorForState(mEndBackgroundColorStateList)
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    setColors(colors)
                } else {
                    setColor(colors[0])
                }
            }
        }
    }

    private fun setBorderColor() {
        mBorderColorStateList?.also {
            if (mBorderWidth > 0.0f) {
                if (hasNativeStateListAPI()) {
                    setStroke(mBorderWidth.toInt(), mBorderColorStateList)
                } else {
                    setStroke(mBorderWidth.toInt(), getColorForState(mBorderColorStateList))
                }
            }
        }
    }

    private fun hasNativeStateListAPI() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP

    override fun onStateChange(stateSet: IntArray?): Boolean {
        return super.onStateChange(stateSet).let {
            if (mBorderColorStateList != null || mBackgroundColorStateList != null || mStartBackgroundColorStateList != null) {
                setBorderColor()
                setBackgroundColor()
                true
            } else {
                it
            }
        }
    }

    override fun onBoundsChange(r: Rect?) {
        super.onBoundsChange(r)
        r?.also {
            if (mIsRadiusAdjustBounds) {
                cornerRadius = min(it.width() / 2.0f, it.height() / 2.0f)
            }
        }
    }
}
<declare-styleable name="GradientButton">
        <attr name="border_color" format="color|reference" />
        <attr name="border_width" format="dimension|reference" />
        <!--圆角是否自适应最小边-->
        <attr name="is_radius_adjust_bounds" format="boolean" />
        <attr name="all_radius" format="dimension|reference" />
        <attr name="top_left_radius" format="dimension|reference" />
        <attr name="top_right_radius" format="dimension|reference" />
        <attr name="bottom_left_radius" format="dimension|reference" />
        <attr name="bottom_right_radius" format="dimension|reference" />
        <attr name="background_color" format="color|reference" />
        <!--渐变色方向-->
        <attr name="orientation" format="enum">
            <enum name="top_bottom" value="0" />
            <enum name="tr_bl" value="1" />
            <enum name="right_left" value="2" />
            <enum name="br_tl" value="3" />
            <enum name="bottom_top" value="4" />
            <enum name="bl_tr" value="5" />
            <enum name="left_right" value="6" />
            <enum name="tl_br" value="7" />
        </attr>
        <attr name="start_background_color" format="color|reference" />
        <attr name="center_background_color" format="color|reference" />
        <attr name="end_background_color" format="color|reference" />
        <attr name="background_alpha" format="fraction" />
        <attr name="padding" format="dimension|reference" />
        <attr name="padding_left" format="dimension|reference" />
        <attr name="padding_top" format="dimension|reference" />
        <attr name="padding_right" format="dimension|reference" />
        <attr name="padding_bottom" format="dimension|reference" />
        <attr name="min_width" format="dimension|reference" />
        <attr name="min_height" format="dimension|reference" />
  </declare-styleable>

就是这么简单,我们只需要提供相应的color选择器,或者背景色值即可完成我们平时需要使用一大堆shapeselector才能实现的效果,最后再看看效果图吧,正所谓无图无真相,嘿嘿

gradientbutton.png

好了,今天的收获就是这么多O(∩_∩)O

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354