Android 自定义View -- 自定义通用Button,避免创建大量布局文件

前提:

在开发中,我们会经常使用到按钮,而且大多数按钮的背景、圆角、按压效果等等都不一样,通常的做法是写大量的shape、selector文件作为background,这样一来,就会创建大量的文件,而且写起来也比较烦,浪费很多时间,所以我想通过自定义一个view,来解决这个问题。

目标:

自定义一个button,所需要的圆角、背景颜色、字体颜色等属性,都是可配置的,还需要实现按压效果,不可用状态。

动手实现:

撸起袖子开始干!

第一步:自定义属性

首先我们要先定义好这些属性,方便在xml中传入值,在attrs.xml下添加如下代码

        <declare-styleable name="CustomButton">
        <!--默认背景颜色-->
        <attr name="bgNormalColor" format="color"/>
        <!--按压时背景颜色-->
        <attr name="bgPressColor" format="color"/>
        <!--默认文字颜色-->
        <attr name="textNormalColor" format="color" />
        <!--按压文字颜色-->
        <attr name="textPressColor" format="color" />
        <!--不可用状态背景颜色-->
        <attr name="bgUnableColor" format="color" />
        <!--不可用状态文字颜色-->
        <attr name="textUnableColor" format="color" />
        <!--圆角半径-->
        <attr name="radius" format="dimension"/>
    </declare-styleable>

属性的意思注释写的很清楚了。

第二步:获取属性

定义好了这些属性,我们要在自定义view中读取这些属性

public class CustomButton extends AppCompatTextView {

    private Paint mPaint;
    private int bgNormalColor,bgPressColor,textPressColor,textNormalColor,bgUnableColor,textUnableColor;
    private float radius;
    private Paint textPaint;

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomButton);
        bgNormalColor = typedArray.getResourceId(R.styleable.CustomButton_bgNormalColor,R.color.red);
        bgPressColor = typedArray.getResourceId(R.styleable.CustomButton_bgPressColor,R.color.red);
        textNormalColor = typedArray.getResourceId(R.styleable.CustomButton_textNormalColor,R.color.white);
        textPressColor = typedArray.getResourceId(R.styleable.CustomButton_textPressColor,R.color.white);
        bgUnableColor = typedArray.getResourceId(R.styleable.CustomButton_bgUnableColor,R.color.gray);
        textUnableColor = typedArray.getResourceId(R.styleable.CustomButton_textUnableColor,R.color.white);
        radius = typedArray.getDimension(R.styleable.CustomButton_radius,5);
        typedArray.recycle();
        init();
    }

    private void init(){
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setStyle(Paint.Style.FILL);
    }

}

通过TypedArray我们读取了这些属性,读取完要记得调用 recycle()方法回收。

第三步:画背景

这里我们应该使用带圆角的方形作为背景,所以我们使用drawRoundRect方法,重写onDraw()方法

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        rect.set(0, 0, getWidth(), getHeight());
        mPaint.setColor(getResources().getColor(bgNormalColor));
        canvas.drawRoundRect(rect,radius,radius,mPaint);
    }

这样我们就画出带圆角的button背景

第四步:画文字

画文字我们使用的是 drawText(text, x, y, paint)方法,需要注意的是这里的y坐标是文字的baseline坐标,具体解释可以看下图


5017748-0fd8d5f2a4e531a0.png

top:可绘制的最高高度所在线
ascent:系统推荐的,在绘制单个字体时,字符应当的最高高度所在线。
baseline:字符基线
descent:系统推荐的,在绘制单个字体时,字符应当的最低高度所在线。
bottom:可绘制的最低高度所在线

我们的buttong中的文字,一般都是居中的,横向居中比较很好办,首先x的坐标通过getWidth()/2就能获得,然后调用 textPaint.setTextAlign(Paint.Align.CENTER),让文字相对于x坐标居中就可以了。
纵向居中就比较麻烦了,我们需要让文字的横向中间线,也就是上图中间的那条红线,处于Button的横向中间线上。通过getHeight()/2我们可以的到buttong中间线的y坐标,这也是文字的中间线y坐标,因为这个中间线到top和bottom的距离相等,得到这个距离,再加上中间线的y轴坐标,就能得到bottom y轴坐标,根据bottom坐标可以得到baseline坐标,这就要使用到FontMetrics类了,这个类中有四个成员变量

FontMetrics:acsent = assent线的y坐标 - baseline 线坐标
FontMetrics:descent = descent线的y坐标 - baseline 线坐标
FontMetrics:top = top线的y坐标 - baseline 线坐标
FontMetrics:bottom = bottom线的y坐标 - baseline 线坐标

注意,这里的acsent 、descent、top、bottom与现实中的acsent 、descent、top、bottom四条线不是一个概念!FontMetrics中的属性是用来计算这些线的。

通过(FontMetrics.bottom -FontMetrics.top)/2可以得到字体的中间线到bottom的距离,然后通过getHeight()/2 +(FontMetrics.bottom -FontMetrics.top)/2得到bottom线的y坐标,再根据上面的FontMetrics:bottom = bottom线的y坐标 - baseline 线坐标就推算出baseline 线坐标 = getHeight()/2 +(FontMetrics.bottom -FontMetrics.top)/2 -FontMetrics.bottom,具体代码如下

    float baseLine = (float) getHeight()/2 +(fm.bottom -fm.top)/2 -fm.bottom;
    textPaint.setColor(getResources().getColor(textNormalColor));
    canvas.drawText(getText().toString(),(float) getWidth()/2,baseLine,textPaint);

这样我们就画出了normal状态下的buttong的背景和文字。

第四部:实现按压效果

按压效果就是当手指按下的时候,背景颜色和字体颜色发生改变,抬起手指恢复。这里的思路是,判断手指触摸的位置是否再按钮范围内,如果是,改变颜色。

首先复写 onTouchEvent方法,记录手指按下的坐标,当手指抬起时将坐标改为(-1,-1)

 @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mEnable) {
            mx = (int) event.getX();
            my = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                invalidate();
                return true;
            } else if (event.getAction() == MotionEvent.ACTION_UP ) {
                performClick();
                mx = -1;
                my = -1;
            }
            invalidate();
        }
        return super.onTouchEvent(event);
    }

然后在onDraw方法中,通过rectcontains(x,y)判断坐标是否再按钮上

           if(rect.contains(mx,my)) {
                mPaint.setColor(getResources().getColor(bgPressColor));
                canvas.drawRoundRect(rect,radius,radius,mPaint);
                textPaint.setColor(getResources().getColor(textPressColor));
            }else {
                mPaint.setColor(getResources().getColor(bgNormalColor));
                canvas.drawRoundRect(rect,radius,radius,mPaint);
                textPaint.setColor(getResources().getColor(textNormalColor));
            }
            canvas.drawText(getText().toString(),(float) getWidth()/2,baseLine,textPaint);

这样就实现了所谓的按压效果

第五步:实现不可用状态

按钮的不可用状态,一般都是将按钮置灰或者其他颜色,并且不可点击,这里通过isEnabled()方法判断是否可用,在onDraw方法里

    if(isEnabled()){
            if(rect.contains(mx,my)) {
                mPaint.setColor(getResources().getColor(bgPressColor));
                canvas.drawRoundRect(rect,radius,radius,mPaint);
                textPaint.setColor(getResources().getColor(textPressColor));
            }else {
                mPaint.setColor(getResources().getColor(bgNormalColor));
                canvas.drawRoundRect(rect,radius,radius,mPaint);
                textPaint.setColor(getResources().getColor(textNormalColor));
            }
            canvas.drawText(getText().toString(),(float) getWidth()/2,baseLine,textPaint);
        }else {
            mPaint.setColor(getResources().getColor(bgUnableColor));
            canvas.drawRoundRect(rect,radius,radius,mPaint);
            textPaint.setColor(getResources().getColor(textUnableColor));
            canvas.drawText(getText().toString(),(float) getWidth()/2,baseLine,textPaint);
        }

这样这个自定义按钮就完成啦!
下面是全部代码

public class CustomButton extends AppCompatTextView {

    private Paint mPaint;
    private RectF rect;
    private int mx = -1,my = -1;
    private int bgNormalColor,bgPressColor,textPressColor,textNormalColor,bgUnableColor,textUnableColor;
    private float radius;
    private Paint textPaint;
    private boolean mEnable = true;
    private Rect heightBounds ,widthBounds;

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomButton);
        bgNormalColor = typedArray.getColor(R.styleable.CustomButton_bg_color_normal, getResources().getColor(R.color.colorPrimary));
        bgPressColor = typedArray.getColor(R.styleable.CustomButton_bg_color_press,getResources().getColor(R.color.colorAccent));
        textNormalColor = typedArray.getColor(R.styleable.CustomButton_text_color_normal,getResources().getColor(R.color.colorWhite));
        textPressColor = typedArray.getColor(R.styleable.CustomButton_text_color_press,getResources().getColor(R.color.colorWhite));
        bgUnableColor = typedArray.getColor(R.styleable.CustomButton_bg_color_unable,getResources().getColor(R.color.colorGray));
        textUnableColor = typedArray.getColor(R.styleable.CustomButton_text_color_unable,getResources().getColor(R.color.colorWhite));
        radius = typedArray.getDimension(R.styleable.CustomButton_button_radius,5);
        typedArray.recycle();
        init();
    }

    private void init(){
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setStyle(Paint.Style.FILL);

        rect = new RectF();
        heightBounds = new Rect();
        widthBounds = new Rect();
    }

    /**
     * 适配 AT_MOST
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int heightMode = View.MeasureSpec.getMode(heightMeasureSpec);
        int widthMode = View.MeasureSpec.getMode(widthMeasureSpec);

        int height = View.MeasureSpec.getSize(heightMeasureSpec);
        int width = View.MeasureSpec.getSize(widthMeasureSpec);

        textPaint.setTextSize(getTextSize());
        textPaint.setTypeface(getTypeface());

        if(View.MeasureSpec.AT_MOST == heightMode){
            textPaint.getTextBounds(getText().toString(),0,getText().toString().length(),heightBounds);
            height = heightBounds.height() + getPaddingTop() + getPaddingBottom();
        }

        if(View.MeasureSpec.AT_MOST == widthMode){
            textPaint.getTextBounds(getText().toString(),0,getText().toString().length(),widthBounds);
            width = widthBounds.width()  + getPaddingLeft() + getPaddingRight();
        }


        setMeasuredDimension(width,height);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        rect.set(0, 0, getWidth(), getHeight());
        Paint.FontMetrics fm = textPaint.getFontMetrics();
        //获取基线坐标
        float baseLine = (float) getHeight()/2 +(fm.bottom -fm.top)/2 -fm.bottom;
        if(isEnabled()){
            if(rect.contains(mx,my)) {
                mPaint.setColor(bgPressColor);
                canvas.drawRoundRect(rect,radius,radius,mPaint);
                textPaint.setColor(textPressColor);
            }else {
                mPaint.setColor(bgNormalColor);
                canvas.drawRoundRect(rect,radius,radius,mPaint);
                textPaint.setColor(textNormalColor);
            }
            canvas.drawText(getText().toString(),(float) getWidth()/2+getPaddingLeft()-getPaddingRight(),baseLine+getPaddingTop()-getPaddingBottom(),textPaint);
        }else {
            mPaint.setColor(bgUnableColor);
            canvas.drawRoundRect(rect,radius,radius,mPaint);
            textPaint.setColor(textUnableColor);
            canvas.drawText(getText().toString(),(float) getWidth()/2+getPaddingLeft()-getPaddingRight(),baseLine+getPaddingTop()-getPaddingBottom(),textPaint);
        }


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mEnable) {
            mx = (int) event.getX();
            my = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                invalidate();
                return true;
            } else if (event.getAction() == MotionEvent.ACTION_UP ) {
                performClick();
                mx = -1;
                my = -1;
            }
            invalidate();
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    @Override
    public void setBackgroundColor(int color) {
        bgNormalColor = color;
        invalidate();
    }

    @Override
    public void setTextColor(int color) {
        textNormalColor = color;
        invalidate();
    }
}

这个自定义button可能还存在很多问题,后续再继续完善吧。

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

推荐阅读更多精彩内容