Android開發自定義圓角帶點選效果的Button
阿新 • • 發佈:2019-01-28
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())