Android开发自定义圆角带点击效果的Button

public class AnimationButton extends Button {

    private int mBackGroundColor = Color.parseColor("#ffffff");
    private int normalColor;
    private int pressedColor;
    private float round;

    //默认画笔
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public AnimationButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        //获取自定义属性
        if (attrs != null) {
            TypedArray typedArray =context.obtainStyledAttributes(attrs,R.styleable.MyRoundButton);

            normalColor = typedArray.getColor(R.styleable.MyRoundButton_normalColor,getResources().getColor(R.color.btn_blue_bg));
            pressedColor = typedArray.getColor(R.styleable.MyRoundButton_pressedColor,getResources().getColor(R.color.btn_main_pressed));
            round = typedArray.getDimension(R.styleable.MyRoundButton_round,10);

            mBackGroundColor = normalColor;
            typedArray.recycle();
        }

        //设置抗锯齿
        mPaint.setAntiAlias(true);
        //设置防抖动
        mPaint.setDither(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //画笔颜色
        mPaint.setColor(mBackGroundColor);

        RectF mBackGroundRect = new RectF(0,0,canvas.getWidth(),canvas.getHeight());
        //绘制背景 圆角矩形
        if (mBackGroundRect != null) {
            canvas.drawRoundRect(mBackGroundRect, round, round, mPaint);
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        //刷新
        invalidate();
        //判断点击操作
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mBackGroundColor = normalColor;

                break;
            case MotionEvent.ACTION_MOVE:

                break;
            case MotionEvent.ACTION_UP:
                mBackGroundColor = pressedColor;

                break;
            case MotionEvent.ACTION_CANCEL:

                break;
        }
        return super.onTouchEvent(event);
    }




}

重点:

1.invalidate(),它会调onDraw()

2.RectF mBackGroundRect = new RectF(0,0,canvas.getWidth(),canvas.getHeight())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值