Android: How to handle right to left swipe gestures

前端 未结 22 1215
日久生厌
日久生厌 2020-11-21 06:18

I want my app to recognize when a user swipes from right to left on the phone screen.

How to do this?

22条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 07:12

    I know its a bit late since 2012 but I hope it will help someone since I think it's a shorter and cleaner code than most of the answers:

    view.setOnTouchListener((v, event) -> {
            
    int action = MotionEventCompat.getActionMasked(event);
    
    switch(action) {
        case (MotionEvent.ACTION_DOWN) :
            Log.d(DEBUG_TAG,"Action was DOWN");
            return true;
    
        case (MotionEvent.ACTION_MOVE) :
            Log.d(DEBUG_TAG,"Action was MOVE");
            return true;
    
        case (MotionEvent.ACTION_UP) :
            Log.d(DEBUG_TAG,"Action was UP");
            return true;
    
        case (MotionEvent.ACTION_CANCEL) :
            Log.d(DEBUG_TAG,"Action was CANCEL");
            return true;
    
        case (MotionEvent.ACTION_OUTSIDE) :
            Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
                    "of current screen element");
            return true;
    
        default :
            return super.onTouchEvent(event);
    }
        });
    

    of course you can leave only the relevant gestures to you.

    src: https://developer.android.com/training/gestures/detector

提交回复
热议问题