自定义view,可拖动

来源:互联网 发布:实时油价查询软件 编辑:程序博客网 时间:2024/05/17 04:54

public class MyView extends View {
 private Paint p;
 private int width = 20;
 private int height = 30;
 private float x = 10;
 private float y = 30;

 public MyView(Context context) {
  super(context);
  p = new Paint();
  p.setColor(Color.BLUE);
 }

 public MyView(Context context, AttributeSet attrs) {
  super(context, attrs);
  p = new Paint();
  p.setColor(Color.BLUE);

 }

 @Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  canvas.drawRect(x, y, x + width, y + height, p);

 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  switch (event.getAction()) {
  case MotionEvent.ACTION_DOWN:
   x = this.getX();
   y = this.getY();
   break;
  case MotionEvent.ACTION_MOVE:
   x = event.getX();
   y = event.getY();
   invalidate();
   break;
  case MotionEvent.ACTION_UP:

   break;
  }
  return super.onTouchEvent(event);
 }

}

0 0
原创粉丝点击