Search code examples
androidclassviewextendontouchlistener

Anyone know how to attach a touch listener to this class?


package com.ewebapps;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

public class Dot extends View {
     private final float x;
     private final float y;
     private final int r;
     private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
     private final Paint mWhite = new Paint(Paint.ANTI_ALIAS_FLAG);

     public Dot(Context context, float x, float y, int r) {
         super(context);
         mPaint.setColor(0xFF000000); //Black
         mWhite.setColor(0xFFFFFFFF); //White
         this.x = x;
         this.y = y;
         this.r = r;
     }

     @Override
     protected void onDraw(Canvas canvas) {
         super.onDraw(canvas);
         canvas.drawCircle(x, y, r+2, mWhite); //White stroke.
         canvas.drawCircle(x, y, r, mPaint); //Black circle.
     }

}

Solution

  • Well... when creating your own views, the best way to accomplish that is overriding the dispatchTouchEvent method. Trust me, using setOnTouchListener and onTouchEvent don't work well in some scenarios. This is all you have to do in your View:

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        // put your logic here  
    
        return super.dispatchTouchEvent(event);
    }