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

来源:互联网 发布:It 门槛 编辑:程序博客网 时间:2024/06/16 13:46
配置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);
@Overrideprotected 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);}@Overridepublic 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;}
0 0
原创粉丝点击