配置XML
<!--styleable-->
<resources>
<declare-styleable name="MyView">
<attr name="Colorouter" format="color|reference"> </attr>
<attr name="Colowithin" format="color|reference"> </attr>
</declare-styleable>
</resources>
//自定义属性
TypedArray type=context.obtainStyledAttributes(attrs,R.styleable.MyView);
colorouter = type.getColor(R.styleable.MyView_Colorouter, Color.WHITE);
colowithin = type.getColor(R.styleable.MyView_Colowithin, Color.WHITE);
@Override
protected void onDraw(Canvas canvas) {//重写绘制
super.onDraw(canvas);
this.setBackgroundResource(R.color.colorluse);
Paint pa=new Paint();
measuredWidth = getMeasuredWidth();//获取当前大小
measuredHeight = getMeasuredHeight();
pa.setColor(getResources().getColor(R.color.colorhuangse));
pa.setStrokeWidth(20);
pa.setStyle(Paint.Style.FILL);
width = (measuredWidth / 2);
height = (measuredHeight / 2);
huangse = width;
canvas.drawCircle(width, height, huangse,pa);
pa.setColor(getResources().getColor(R.color.colorbaise));//设置颜色
baiseewidth = width / 2;
canvas.drawCircle(width, height, baiseewidth,pa);
Rect rect = new Rect();
String str="圆环";//设置内容
pa.setTextSize(20);
pa.setColor(Color.BLACK);
pa.getTextBounds(str,0,str.length(),rect);
canvas.drawText(str, width -rect.width()/2, height +rect.height()/2,pa);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN://触摸
float pointX = event.getX();
float pointY = event.getY();
double range = Math.sqrt(( width - pointX) * (width - pointX) + ( height- pointY) * (height - pointY));
text = "";
if (range <baiseewidth) {
text = "在小圆内";
GetText.Get(text);//接口回调返回
} else if (range >baiseewidth && range <huangse ) {
text = "在圆环内";
GetText.Get(text);
} else if (range > huangse) {
text = "在圆环外";
GetText.Get(text);
}
}
return true;
}