public class MyView extends AppCompatTextView { private Paint paint; private boolean flag=true; private void init(){ paint = new Paint(); //设置抗锯齿 paint.setAntiAlias(true); } public MyView(Context context) { super(context); init(); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override protected void onDraw(Canvas canvas) { //四位随机数 int s = (int) (Math.random() * 9000) + 1000; //在屏幕上画一个矩形 paint.setStyle(Paint.Style.FILL); if(flag == true){ paint.setColor(Color.RED); }else { paint.setColor(Color.BLUE); } //在屏幕上画一个矩形 canvas.drawRect(100,100, 200,150,paint); if(flag == true){ paint.setColor(Color.BLACK); }else { paint.setColor(Color.RED); } paint.setTextSize(22); canvas.drawText(s+"",120,130,paint); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN){ }else if(event.getAction() == MotionEvent.ACTION_MOVE){ }else { invalidate(); if(flag == true){ flag = false; }else { flag = true; } } return true; } }![]()
自定义view,点击更换背景色与随机数
最新推荐文章于 2021-05-25 21:27:17 发布