自定义控件之单点触摸监听

配置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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值