自定义一个跟随手指的小球
DrawView.java文件
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class DrawView extends View{ public float currentX=40; public float currentY=50; Paint p=new Paint();//定义画笔 public DrawView(Context context) { super(context); } //构造器一定要有否则报错 public DrawView(Context context, AttributeSet attrs){ super(context, attrs); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); p.setColor(Color.RED); canvas.drawCircle(currentX, currentY, 15, p);//画圆形 } @Override public boolean onTouchEvent(MotionEvent event) { currentX=event.getX(); currentY=event.getY(); //通知组件重绘制 this.invalidate(); return true; } }
layout.xml加入
<com.layer.study3027.DrawView android:layout_width="fill_parent" android:layout_height="wrap_content" />