Android新优化

Android 自定义View -- 自定义通用Button,避

2019-09-30  本文已影响0人  程序员WW

前提:

在开发中,我们会经常使用到按钮,而且大多数按钮的背景、圆角、按压效果等等都不一样,通常的做法是写大量的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可能还存在很多问题,后续再继续完善吧。

上一篇下一篇

猜你喜欢

热点阅读