首先,定义一个类,继承view,实现一个构造器,里面设置的属性是在values一个自定义的attrs中定义的,
public class CircleView extends View { private float circle_x; private float circle_y; private float circle_radius; private Paint paint; public CircleView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); //找到设定好的attrs中的xml TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView); //设置圆心的x值,如果没有在xml中设置,就使用后面的默认值 circle_x = a.getDimension(R.styleable.CircleView_circle_x, 50); //设置圆心的Y值 circle_y = a.getDimension(R.styleable.CircleView_circle_y, 50); //设置圆的颜色 int color = a.getColor(R.styleable.CircleView_circle_color, Color.BLUE); //设置圆的半径 circle_radius = a.getDimension(R.styleable.CircleView_circle_radius, 30); a.recycle(); //设置画笔 paint = new Paint(); //设置颜色 paint.setColor(color); //设置实心或者空心圆 paint.setStyle(Paint.Style.FILL); paint.setAntiAlias(true); //设置空心圆的边线的宽度 paint.setStrokeWidth(10); } //绘制画布 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //绘制圆 canvas.drawCircle(circle_x,circle_y,circle_radius,paint); } //使定义好的可以拖动,需要重写方法,监听屏幕的点击 @Override public boolean onTouchEvent(MotionEvent event) { //得到点击的xy,可以查找一个freenDAO circle_x=event.getX(); circle_y= event.getY(); Log.e("------","circle_x"+circle_x+" circle_y"+circle_y); invalidate(); return true; } }
在values中创建一个attrs.xml,用来放属性
<resources> <!--名字与自定义view的类名一样--> <declare-styleable name="CircleView"> <!--自定义圆的颜色--> <attr name="circle_color" format="color"></attr> <!--自定义颜色的半径--> <attr name="circle_radius" format="dimension"></attr> <!--圆心x轴--> <attr name="circle_x" format="dimension"></attr> <!--圆心y轴--> <attr name="circle_y" format="dimension"></attr> </declare-styleable> </resources>然后在需要的布局中调用就可以了