Search code examples
androidonclickandroid-canvasonlongclicklistener

How to detect click and longClick on canvas


Hi i'm working on a Battleships game in Android and currently i'm trying to implement the ship positioning activity.

I have a custum view with onDraw representing the board on which you position the ships.

I want to be able to rotate ships by singletapping them and drag a ship by longclicking it. The thing is i can't just use onClick and onLongClick because i need to know where was the click on the canvas. I tried using onTouch but that didn't work. I also tried using GestureDetector but it just meseed up everything.

Do you have any suggestions on how to approach this logic?


Solution

  • i need to know where was the click on the canvas

    You have a custom view, hence you can easily use GestureDetector.SimpleOnGestureListener. Just override the onTouchEvent() of your CustomView and use the onLongPress of the GestureDetector. I would suggest you to handle this within the CustomView itself, rather than do it in Activity or Fragment. This would keep things modularized.

    You can follow the code below to get this done:

    CustomView.java

    public class CustomView extends View {
    
            private GestureDetectorCompat mGestureDetector;
            private LongPressGestureListener longPressGestureListener;
    
            CustomView(Context context, AttributeSet attrs) {
                super(context, attrs);
                longPressGestureListener= new LongPressGestureListener(this);
                mGestureDetector = new GestureDetectorCompat(context, longPressGestureListener);
            }
    
            @Override
            public boolean onTouchEvent(MotionEvent event) {
                mGestureDetector.onTouchEvent(event);
                // Handle any other event here, if not long press.
                return true;
            }
    }
    

    LongPressGestureListener.java

    public class LongPressGestureListener extends GestureDetector.SimpleOnGestureListener {
    
            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
                // e will give you the location and everything else you want
                // This is where you will be doing whatever you want to.
                int eIndex = MotionEventCompat.getActionIndex(e);
                float eX = MotionEventCompat.getX(e, eIndex);
                float eY = MotionEventCompat.getY(e, eIndex);
                Log.d("X:Y = " + eX + " : " + eY);
            }
    
            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
    }