Learn GestureDetector in Android using easy to understand examples.

Example 1: Simple GestureDetector

A simple gesturedetector example.

Step 1: Create Project

The first step is to create a Android Project in Android Studio.

Step 2: Add Dependencies

No external dependencies are needed for this project.

Step 3: Design Layouts

Add an ImageView to our activity_main.xml layout as follows:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <ImageView
        android:id="@+id/image"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/G"/>

</RelativeLayout>

Step : Write Code

Here’s the full code:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    GestureDetector myGestureDetector;

    class myGestureListener extends GestureDetector.SimpleOnGestureListener{
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if ((e1.getX()-e2.getX())>50){
                Toast . MakeText( MainActivity . This , " Swipe from right to left " , Toast . LENGTH_LONG ) . Show();
            }else if((e2.getX()-e1.getX())>50){
                Toast . MakeText( MainActivity . This , " Swipe from left to right " , Toast . LENGTH_LONG ) . Show();
            }

            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super . onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        myGestureDetector = new GestureDetector(MainActivity.this,new myGestureListener());
        imageView = (ImageView) findViewById(R.id.image);
        imageView.setOnTouchListener(new View.OnTouchListener() {
            @Override // You can get the event event sent by the touch screen
            public boolean onTouch(View v, MotionEvent event) {

                // Forward events
                myGestureDetector.onTouchEvent(event);
                return true;
            }
        });
    }

}

Run

Copy the code into your project or download the code in the reference links below.

Reference

Find the reference links below:

Number Link
1. Download code
2. Follow code author