Saturday, December 13, 2014

Detect Gestures of Swipe to switch between activity

Example to detect Gestures of Swipe using GestureDetectorCompat, to switch between activity by override onFling() of GestureDetector.SimpleOnGestureListener.


In main activity, override onFling() to switch to SecondActivity if Swipe left Gestures detected.
package com.example.androidswipeactivity;

import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {
 
 private GestureDetectorCompat gestureDetectorCompat;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  gestureDetectorCompat = new GestureDetectorCompat(this, new MyGestureListener());
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  this.gestureDetectorCompat.onTouchEvent(event);
        return super.onTouchEvent(event);
 }

 class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
  //handle 'swipe left' action only

        @Override
        public boolean onFling(MotionEvent event1, MotionEvent event2, 
                float velocityX, float velocityY) {
            
         /*
         Toast.makeText(getBaseContext(), 
          event1.toString() + "\n\n" +event2.toString(), 
          Toast.LENGTH_SHORT).show();
         */
         
         if(event2.getX() < event1.getX()){
          Toast.makeText(getBaseContext(), 
           "Swipe left - startActivity()", 
           Toast.LENGTH_SHORT).show();
          
          //switch another activity
             Intent intent = new Intent(
               MainActivity.this, SecondActivity.class);
             startActivity(intent);
         }

            return true;
        }
    }
}

/res/layout/activity_main.xml, layout for MainActivity
<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:background="@color/background_material_dark"
    tools:context="com.example.androidswipeactivity.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher"/>

</LinearLayout>

SecondActivity.java, second activity, override onFling() to switch to finish() if Swipe right Gestures detected. It create ContentView using java code without xml.
package com.example.androidswipeactivity;

import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.Toast;

public class SecondActivity extends ActionBarActivity {
 
 private GestureDetectorCompat gestureDetectorCompat;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  TextView text2ndActivity = new TextView(this);
  text2ndActivity.setText("Second Activity");
  setContentView(text2ndActivity);
  
  gestureDetectorCompat = new GestureDetectorCompat(this, new My2ndGestureListener());
 }
 
 @Override
 public boolean onTouchEvent(MotionEvent event) {
  this.gestureDetectorCompat.onTouchEvent(event);
        return super.onTouchEvent(event);
 }

 class My2ndGestureListener extends GestureDetector.SimpleOnGestureListener {
  //handle 'swipe right' action only

        @Override
        public boolean onFling(MotionEvent event1, MotionEvent event2, 
                float velocityX, float velocityY) {
            
         /*
         Toast.makeText(getBaseContext(), 
          event1.toString() + "\n\n" +event2.toString(), 
          Toast.LENGTH_SHORT).show();
         */
         
         if(event2.getX() > event1.getX()){
          Toast.makeText(getBaseContext(), 
           "Swipe right - finish()", 
           Toast.LENGTH_SHORT).show();
          
          finish();
         }

            return true;
        }
    }

}

Make sure to modify AndroidManifest.xml to add <activity> of SecondActivity.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidswipeactivity"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SecondActivity"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>


download filesDownload the files.

Next:
Swipe to Slide animated activity switching

2 comments:

Unknown said...

Works like a charm, i forget to Override a onTouchEvent()

Anonymous said...

Easy and clean , thanx