Search code examples
androidandroid-custom-viewontouchlistener

onTouchEvent is not getting executed


I am implementing a simple custom view basically for getting a hang of android canvas. This is a simple tictactoe board.

Here is the Custom view class :

public class BoardInterface extends View implements View.OnTouchListener{

    private int board_width, board_height;
    private final Context context;

    public BoardInterface(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        board_width = canvas.getWidth();
        board_height = canvas.getHeight();


        Paint paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(20);

        canvas.drawLine((board_width/5)*2, (board_height/6), (board_width/5)*2, ((board_height/6)*5), paint);
        canvas.drawLine(((board_width/5)*3), (board_height/6), ((board_width/5)*3), ((board_height/6)*5), paint);

        canvas.drawLine((board_width/6), ((board_height/7)*3), ((board_width/6)*5), ((board_height/7)*3), paint);
        canvas.drawLine((board_width/6), ((board_height/7)*4), ((board_width/6)*5), ((board_height/7)*4), paint);

        super.onDraw(canvas);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int x, y;
        Log.d("TOUCH", "WORKS");
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            x = (int) Math.floor(event.getX());
            y = (int) Math.floor(event.getY());
            Toast.makeText(context, String.valueOf(x) + "," + String.valueOf(y), Toast.LENGTH_SHORT).show();
        }
        return super.onTouchEvent(event);
    }
}

I've set a OnTouchListener and override that to show a simple toast. Nothing comes on screen i.e the toas, nor do I get the Log.D() message in logcat.

What am I missing here ?


Solution

  • Try to override instead of onTouch method the following method.

    @Override
    public boolean onTouchEvent(MotionEvent event){....}
    

    If the touch event still doesn't gets called call somewhere in your constructor

    setClickable(True);