### 新建类CustomView 继承View
### main布局
<com.example.myapplication_view.CustomView android:layout_width="wrap_content" android:layout_height="wrap_content" />
### MainActivity
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //一个参数的构造方法调用 // CustomView view = new CustomView(this); // setContentView(view); setContentView(R.layout.activity_main);//两个参数的构造方法调用 } }
### CustomView类
public class CustomView extends View { private static final int WIDTH = 90; private Rect rect = new Rect(0, 0, WIDTH, WIDTH);//绘制矩形的区域 private int deltaX,deltaY;//点击位置和图形边界的偏移量 // private int moveX,moveY; private static Paint paint = new Paint();//画笔 public CustomView(Context context) { super(context); paint = new Paint(); paint.setColor(Color.BLUE);//填充蓝色 paint.setAntiAlias(true); } public CustomView(Context context, AttributeSet attrs) { super(context, attrs); paint = new Paint(); paint.setColor(Color.RED);//填充红色 paint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(rect.centerX(),rect.centerY(),WIDTH/2, paint);//画矩形 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public boolean onTouchEvent (MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: if(!rect.contains(x, y)) { return false;//没有在矩形上点击,不处理触摸消息 } deltaX = x - rect.left; deltaY = y - rect.top; break; case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: Rect old = new Rect(rect); // 更新矩形的位置 rect.left = x - deltaX; rect.top = y - deltaY; rect.right = rect.left + WIDTH; rect.bottom = rect.top + WIDTH; old.union(rect);//要刷新的区域,求新矩形区域与旧矩形区域的并集 invalidate(old);//出于效率考虑,设定脏区域,只进行局部刷新,不是刷新整个view break; } return true;//处理了触摸消息,消息不再传递 } }