* onMeasure 测量方法 * onLayout 摆放位置--在自定义ViewGroup的时候需要使用 * onDraw 用来绘制 */ public class CustomView extends View { Paint paint; char [] array = new char[4]; Random r = new Random(); float downX = 0; // 1、在类中直接使用new关键字实例化控件时使用的构造方法 public CustomView(Context context) { super(context); init(); } private void init() { // 实例化画笔 paint = new Paint(); // 抗锯齿 paint.setAntiAlias(true); // 设置画出来的颜色 paint.setColor(Color.RED); // 设置画笔的粗细 paint.setStrokeWidth(10); } // 2、在布局文件中创建的控件 使用的是第一个构造方法 public CustomView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public CustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // canvas.drawLine(0,0,100,100,paint); // paint.setColor(Color.YELLOW); // canvas.drawCircle(200,200,100,paint); // Bitmap bit = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); // canvas.drawBitmap(bit,300,300,paint); for (int i = 0; i <4 ; i++) { String a = r.nextInt(10) + ""; char [] temp = a.toCharArray(); array[i] = temp[0]; } canvas.drawRect(100,100,300,200,paint); paint.setColor(Color.CYAN); paint.setTextSize(80); canvas.drawText(array,0,4,100,200,paint); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: downX = event.getX(); paint.setColor(Color.RED); invalidate(); break; case MotionEvent.ACTION_UP: float upX = event.getX(); if(upX > 100 && upX < 200){ paint.setColor(Color.BLACK); invalidate(); } break; case MotionEvent.ACTION_MOVE: break; } // return true; return super.onTouchEvent(event); } // 传入activity public void setPaint(){ paint.setColor(Color.GREEN); invalidate(); }}
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.cv).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // ((CustomView)view).setPaint(); Toast.makeText(MainActivity.this,"啦啦啦",Toast.LENGTH_SHORT).show(); } }); } }
<com.custom_.custom.CustomView android:id="@+id/cv" android:layout_width="match_parent" android:layout_height="match_parent" />
自定义控件_View----实现点击更换随机数
最新推荐文章于 2022-11-02 11:57:52 发布