自定义小球跟随手指移动

package com.example.ballviewdemo; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; /** * Created by Administrator on 2017/11/2 0002. */ //自定义类继承视图 public class BallDemo extends View{ private int x = 100; private int y = 100; Context context; public BallDemo(Context context) { this(context,null); }public BallDemo(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); }public BallDemo(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); //设置画笔颜色 paint.setColor(Color.RED); //画圆 canvas.drawCircle(x,y,20,paint); }@Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: x = (int) event.getX(); y = (int) event.getY(); break; } WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); int width = manager.getDefaultDisplay().getWidth(); int height = manager.getDefaultDisplay().getHeight(); if(x>=20&&y>=20&&x<=width-20&&y<=height-90) { invalidate(); } return true; } }

//在主方法的布局中调用视图




    推荐阅读