SoFunction
Updated on 2025-03-04

Android gesture operation example (judgment of up/down/left/right)

This article describes how to operate Android gestures. Share it for your reference, as follows:

Android provides an interface for judging gestures, so we can implement various gesture functions based on the provided API to improve the user experience of mobile phone applications.

Here is a small demo I wrote:

public class GestureActivity extends Activity {
  private GestureDetector gestureDetector;
  private Screen screen;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView();
    gestureDetector = new GestureDetector(this,onGestureListener);
    //Get the screen size    screen = (this);
  }
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    return (event);
  }
   onGestureListener = new (){
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
        float velocityY) {
      float x = () - ();
      float y = () - ();
      //The limit must be passed 1/3 of the screen to be considered as passing      float x_limit =  / 3;
      float y_limit =  / 3;
      float x_abs = (x);
      float y_abs = (y);
      if(x_abs >= y_abs){
        //gesture left or right
        if(x > x_limit || x < -x_limit){
          if(x>0){
            //right
            show("right");
          }else if(x
            //left
            show("left");
          }
        }
      }else{
        //gesture down or up
        if(y > y_limit || y < -y_limit){
          if(y>0){
            //down
            show("down");
          }else if(y
            //up
            show("up");
          }
        }
      }
      return true;
    }
  };
  private void show(String value){
    (this, value, Toast.LENGTH_SHORT).show();
  }
}

public class GestureUtils {
  //Get the screen size  public static Screen getScreenPix(Context context) {
    DisplayMetrics dm = new DisplayMetrics();
    WindowManager windowManager = (WindowManager) (Context.WINDOW_SERVICE);
    ().getMetrics(dm);
    return new Screen(,);
  }
  public static class Screen{
    public int widthPixels;
    public int heightPixels;
    public Screen(){
    }
    public Screen(int widthPixels,int heightPixels){
      =widthPixels;
      =heightPixels;
    }
    @Override
    public String toString() {
      return "("+widthPixels+","+heightPixels+")";
    }
  }
}

For more information about Android related content, please check out the topic of this site:Android file operation skills summary》、《A summary of SD card operation methods for Android programming and development》、《Android development introduction and advanced tutorial》、《Android resource operation skills summary》、《Android View View Tips Summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.