Search code examples
androidxamarinxamarin.androidtouch-event

OnLongPress is not working with our touch events


I am developing a game in which I want to perform certain operations when user single touch the screen, and some other operations when user long press the screen. For this, I have created a Gesture Detector class and add events to them.

Surface View Class

public MySurfaceView(Context context, IAttributeSet attrs):base(context, attrs)
    {
        this.context=context;
        SetWillNotDraw(false);
        gestureDetector = new GestureDetector(context, new GestureListener());

    }

 public override bool OnTouchEvent(MotionEvent e)
    {
        Log.Debug(Tag, "Inside" + System.Reflection.MethodBase.GetCurrentMethod().Name + "Method");
        return gestureDetector.OnTouchEvent(e); 
    }

Gesture Listener Class

  private class GestureListener : GestureDetector.SimpleOnGestureListener
    {
        public override bool OnDown(MotionEvent e)
        {
            Log.Debug("Tag", "Inside Gesture OnDown Event");
            // don't return false here or else none of the other 
            // gestures will work
            return true;

        }

        public override bool OnSingleTapConfirmed(MotionEvent e)
        {
            Log.Debug("Tag", "Inside Gesture OnSingleTapConfirmed Event");

            return true;
        }

        public override bool OnDoubleTap(MotionEvent e)
        {
            Log.Debug("Tag", "Inside Gesture OnDoubleTap Event");
            return true;
        }

        public override void OnLongPress(MotionEvent e)
        {
            Log.Debug("Tag", "Inside Long Press Event");
        }




    }

All events except OnLongPress is working with the above code. After going through the comments of this question. I have to return false for OnDown event. After updating my code base on the comment my OnLongPress event start working but now only OnLongPress event is working.

   public override bool OnDown(MotionEvent e)
        {
            Log.Debug("Tag", "Inside Gesture OnDown Event");
            // don't return false here or else none of the other 
            // gestures will work
            return false;

        }

Is there any way by which I can make OnLongPress work with other events as I need all the events to work together.


Solution

  • Change your OnTouchEvent to the following:

     public override bool OnTouchEvent(MotionEvent e){
         Log.Debug(Tag, "Inside" + System.Reflection.MethodBase.GetCurrentMethod().Name + "Method");
         gestureDetector.OnTouchEvent(e); 
         return true;
    }
    

    You can find the explanation here.