1 跟随手指移动的球
1 package ui; 2 3 import android.content.Context; 4 import android.graphics.Canvas; 5 import android.graphics.Color; 6 import android.graphics.Paint; 7 import android.util.AttributeSet; 8 import android.view.MotionEvent; 9 import android.view.View; 10 11 /** 12 * Created by Administrator on 2016/4/3. 13 */ 14 public class MoveCircle extends View{ 15 public MoveCircle(Context context) { 16 super(context); 17 } 18 19 public MoveCircle(Context context, AttributeSet attrs) { 20 super(context, attrs); 21 } 22 23 public MoveCircle(Context context, AttributeSet attrs, int defStyleAttr) { 24 super(context, attrs, defStyleAttr); 25 } 26 27 float currentX = 50.0f; 28 float currentY = 50.0f; 29 30 @Override 31 protected void onDraw(Canvas canvas) { 32 super.onDraw(canvas); 33 Paint paint = new Paint(); 34 paint.setColor(Color.RED); 35 canvas.drawCircle(currentX,currentY,10,paint); 36 } 37 38 @Override 39 public boolean onTouchEvent(MotionEvent event) { 40 super.onTouchEvent(event); 41 currentX = event.getX(); 42 currentY = event.getY(); 43 //重绘 44 invalidate(); 45 return true; 46 47 } 48 }
1 <ui.MoveCircle 2 android:id="@+id/circle" 3 android:layout_width="wrap_content" 4 android:layout_height="wrap_content" 5 android:minHeight="100dp" 6 android:minWidth="100dp" 7 />