自定义View之自定义按键圆角边框背景添加点击效果

来源:互联网 发布:cf手游刷武器软件 编辑:程序博客网 时间:2024/05/19 02:24

自定义View之自定义按键圆角边框背景添加点击效果

设置边框可以参考前一篇博客

添加后效果如图



1、新添加了几个属性

 <!-- 点击状态 -->        <attr name="isChick" format="boolean"/>        <!--点击后背景颜色-->        <attr name="clickedBgColor" format="color"/>        <!--点击后边框颜色-->        <attr name="clickedCornerRadiusColor" format="color"/>        <!--点击后字体颜色-->        <attr name="clickedTextColor" format="color"/>

相应的效果如注释

2、在定义控件中获取设置的属性

  isChick = typedArray.getBoolean(R.styleable.BgButton_isChick, false);            clickedBgColor = typedArray.getColor(R.styleable.BgButton_clickedBgColor, -1);            clickedCornerRadiusColor = typedArray.getColor(R.styleable.BgButton_clickedCornerRadiusColor, -1);            textColor = getCurrentTextColor();            clickedTextColor = typedArray.getColor(R.styleable.BgButton_clickedTextColor, -1);


3、在设置点击效果的时候其实主要是用不同颜色的画笔进行绘制控件

 if (borderWidth > 0 && borderColor != 0) {            paintBorder = new Paint();            if (isChick) {                paintBorder.setColor(clickedCornerRadiusColor);            } else {                paintBorder.setColor(borderColor);            }            paintBorder.setStyle(Paint.Style.STROKE);            paintBorder.setStrokeWidth(borderWidth);            paintBorder.setAntiAlias(true);        }        paintBg = new Paint();        if (isChick) {            paintBg.setColor(clickedBgColor);            setTextColor(clickedTextColor);        } else {            paintBg.setColor(bgColor);            setTextColor(textColor);        }        paintBg.setAntiAlias(true);        paintBg.setStyle(Paint.Style.FILL);

4、对点击效果后进行重新绘制

 @Override    public boolean onTouchEvent(MotionEvent event) {        if (event.getAction() == MotionEvent.ACTION_DOWN) {            isChick = !isChick;            drawBackgroud(isChick);        }        return super.onTouchEvent(event);    }    private void drawBackgroud(boolean b) {        if (b) {            paintBg.setColor(clickedBgColor);            if (borderWidth > 0 && borderColor != 0) {                paintBorder.setColor(clickedCornerRadiusColor);            }            setTextColor(clickedTextColor);        } else {            paintBg.setColor(bgColor);            if (borderWidth > 0 && borderColor != 0) {                paintBorder.setColor(borderColor);            }            setTextColor(textColor);        }        invalidate();    }


最后GitHub链接和使用方法:https://github.com/cc0819/BgButton



阅读全文
0 0