Android: How to handle right to left swipe gestures

前端 未结 22 1213
日久生厌
日久生厌 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条回答
  •  后悔当初
    2020-11-21 06:58

    Here is simple Android Code for detecting gesture direction

    In MainActivity.java and activity_main.xml, write the following code:

    MainActivity.java

    import java.util.ArrayList;
    
    import android.app.Activity;
    import android.gesture.Gesture;
    import android.gesture.GestureLibraries;
    import android.gesture.GestureLibrary;
    import android.gesture.GestureOverlayView;
    import android.gesture.GestureOverlayView.OnGesturePerformedListener;
    import android.gesture.GestureStroke;
    import android.gesture.Prediction;
    import android.os.Bundle;
    import android.widget.Toast;
    
    public class MainActivity extends Activity implements
            OnGesturePerformedListener {
    
        GestureOverlayView gesture;
        GestureLibrary lib;
        ArrayList prediction;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            lib = GestureLibraries.fromRawResource(MainActivity.this,
                    R.id.gestureOverlayView1);
            gesture = (GestureOverlayView) findViewById(R.id.gestureOverlayView1);
            gesture.addOnGesturePerformedListener(this);
        }
    
        @Override
        public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
            ArrayList strokeList = gesture.getStrokes();
            // prediction = lib.recognize(gesture);
            float f[] = strokeList.get(0).points;
            String str = "";
    
            if (f[0] < f[f.length - 2]) {
                str = "Right gesture";
            } else if (f[0] > f[f.length - 2]) {
                str = "Left gesture";
            } else {
                str = "no direction";
            }
            Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
    
        }
    
    }
    

    activity_main.xml

    
    
        
    
    
    

提交回复
热议问题