public class MyView extends View { private int ny; private int wy; private float textsize; public MyView(Context context) { this(context,null); } public MyView(Context context, AttributeSet attrs) { this(context, attrs,R.style.AppTheme); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //从构造函数中读取attrs中的属性 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.Circle); String text = ta.getString(R.styleable.Circle_text); //第一个参数是属性的id,相当于属性的名字 //第二个参数为默认值,它是在自定义布局中配置的属性不起作用时可以替换 //颜色返回int类型的值 ny = ta.getColor(R.styleable.Circle_ny, Color.WHITE); wy = ta.getColor(R.styleable.Circle_wy, Color.YELLOW); //数值类型要使用getDimension,返回float类型 textsize = ta.getDimension(R.styleable.Circle_textsize, 1); //记得此时要回收recycle ta.recycle(); } //画布的方法 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //实例化第一只画笔 Paint opaint = new Paint(); opaint.setColor(ny); opaint.setAntiAlias(true); opaint.setStyle(Paint.Style.FILL); opaint.setStrokeWidth(1); //画小圆 canvas.drawCircle(getWidth()/2,getHeight()/2,70,opaint); //实例化第二只画笔 Paint tpaint = new Paint(); tpaint.setColor(wy); tpaint.setAntiAlias(true); tpaint.setStyle(Paint.Style.STROKE); tpaint.setStrokeWidth(100); //画中间的圆 canvas.drawCircle(getWidth()/2,getHeight()/2,100,tpaint); //实例化第三只画笔 Paint thpaint = new Paint(); thpaint.setColor(Color.BLACK); thpaint.setAntiAlias(true); thpaint.setStrokeWidth(1); thpaint.setStyle(Paint.Style.STROKE); float yh = thpaint.measureText("圆环"); canvas.drawText("圆环",(getWidth()-yh)/2,getHeight()/2,thpaint); } //重写onTouchEvent方法,实现点击哪里,提示哪里 @Override public boolean onTouchEvent(MotionEvent event) { int x; int y; switch (event.getAction()){ case MotionEvent.ACTION_DOWN: //得到点击的坐标 x = (int) event.getX(); y = (int) event.getY(); int x1 = (x - getWidth() / 2) * (x - getWidth() / 2); int y1 = (y - getHeight() / 2) * (y - getHeight() / 2); //判断点击位置是否在圆内 if (x1+y1<70*70){ Toast.makeText(getContext(),"小圆内",Toast.LENGTH_SHORT).show(); }else if (x1+y1<100*100&&x1+y1>70*70){ Toast.makeText(getContext(),"圆环内",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getContext(),"圆环外",Toast.LENGTH_SHORT).show(); } break; } return true; } } //从构造函数中读取attrs中的属性<resources> <declare-styleable name="Circle"> <attr name="img" format="reference" /> <attr name="text" format="string" /> <attr name="ny" format="color" /> <attr name="wy" format="color" /> <attr name="textsize" format="dimension" /> </declare-styleable> </resources>