Search code examples
javaandroidgesture

How to implement "Two finger swipe" gesture in android?


I have researched a lot but I couldn't find even a blog that tell about MultiTouch events. All are giving tutorials on single swipe. I wish to apply fling and 2 finger swipe both in same activity.


Solution

  • I got the solution myself after trying and failing a lot

    @Override
    public boolean onTouchEvent(MotionEvent event) {
      
    
        Log.d(TAG, "onTouchEvent: " + event.getAction());
        //with the getPointerCount() i'm able to get the count of fingures
        if(event.getPointerCount()>1){
            switch (event.getAction() & MotionEvent.ACTION_MASK)
            {
                case MotionEvent.ACTION_POINTER_DOWN:
                    // This happens when you touch the screen with two fingers
                    mode = SWIPE;
                    // event.getY(1) is for the second finger
                    p1StartY = event.getY(0);
                    p2StartY = event.getY(1);
                    break;
    
                case MotionEvent.ACTION_POINTER_UP:
                    // This happens when you release the second finger
                    mode = NONE;
                    float p1Diff = p1StartY - p1StopY;
                    float p2Diff = p2StartY - p2StopY;
    
                   //this is to make sure that fingers go in same direction and 
                   // swipe have certain length to consider it a swipe
                    if(Math.abs(p1Diff) > DOUBLE_SWIPE_THRESHOLD
                            && Math.abs(p2Diff) >DOUBLE_SWIPE_THRESHOLD &&
                            ( (p1Diff>0 && p2Diff>0) || (p1Diff < 0 && p2Diff<0) ))
                    {
                        if(p1StartY > p1StopY)
                        {
                            // Swipe up
                            doubleSwipeUp();
                        }
                        else
                        {
                            //Swipe down
                            doubleSwipeDown();
                        }
                    }
                    this.mode = NONE;
                    break;
    
                case MotionEvent.ACTION_MOVE:
                    if(mode == SWIPE)
                    {
                        p1StopY = event.getY(0);
                        p2StopY = event.getY(1);
                    }
                    break;
            }
    
        }
        else if(event.getPointerCount() == 1){
           //this is single swipe, I have implemented onFling() here
            this.gestureObject.onTouchEvent(event);
        }
    
        return false;
    }