/** * Created by yyf on 2017/12/14. */ public class SmallBall extends View{ private Paint mPaint; private float cx=60;//绘制点的X坐标 private float cy=50;//绘制点的Y坐标 private float radius=30; //圆的半径 private Context mContext; public SmallBall(Context context) { this(context,null); } public SmallBall(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public SmallBall(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.mContext=context; init(); } private void init(){ mPaint=new Paint(); mPaint.setColor(Color.RED); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawCircle(cx,cy,radius,mPaint); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: setCx(event.getX()); setCy( event.getY()); invalidate(); break; case MotionEvent.ACTION_UP: break; } return true; } public void setCx(float cx) { this.cx = cx; } public void setCy(float cy) { this.cy = cy; } public float getCx() { return cx; } public float getCy() { return cy; } }
2.在activity中的xml引用这个自定义的View 运行ok