Skip to main content

Swipe or OnFling Event Android

This  is a simple application Demonstrating Swipe or onFling() event on ListView.


you can download the source code of this project from  google drive  https://drive.google.com/folderview?id=0BySLpWhqmbbdSVB4M0hXb0VxcU0&usp=sharing
click on the above link ->sign into  your  google account ->add this to your google drive -> open it in google drive and download it.

1.Following is the MainActivity (DemoSwipe.java) of the application

package com.arun.demolistviewswipe;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class DemoSwipe extends Activity {
 ListView lvCountry;
 String[] country = { "India", "USA", "Russsia", "China", "Pakistan",
   "Canada", "UK" };
 SwipeGestureListener gestureListener;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  lvCountry = (ListView) findViewById(R.id.lv_country);
  ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
    DemoSwipe.this, android.R.layout.simple_list_item_1, country);
  lvCountry.setAdapter(arrayAdapter);
  gestureListener = new SwipeGestureListener(DemoSwipe.this);
  lvCountry.setOnTouchListener(gestureListener);

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 class SwipeGestureListener extends SimpleOnGestureListener implements
   OnTouchListener {
  Context context;
  GestureDetector gDetector;
  static final int SWIPE_MIN_DISTANCE = 120;
  static final int SWIPE_MAX_OFF_PATH = 250;
  static final int SWIPE_THRESHOLD_VELOCITY = 200;

  public SwipeGestureListener() {
   super();
  }

  public SwipeGestureListener(Context context) {
   this(context, null);
  }

  public SwipeGestureListener(Context context, GestureDetector gDetector) {

   if (gDetector == null)
    gDetector = new GestureDetector(context, this);

   this.context = context;
   this.gDetector = gDetector;
  }

  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {

   final int position = lvCountry.pointToPosition(
     Math.round(e1.getX()), Math.round(e1.getY()));

   String countryName = (String) lvCountry.getItemAtPosition(position);

   if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
    if (Math.abs(e1.getX() - e2.getX()) > SWIPE_MAX_OFF_PATH
      || Math.abs(velocityY) < SWIPE_THRESHOLD_VELOCITY) {
     return false;
    }
    if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE) {
     Toast.makeText(DemoSwipe.this, "bottomToTop" + countryName,
       Toast.LENGTH_SHORT).show();
    } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE) {
     Toast.makeText(DemoSwipe.this,
       "topToBottom  " + countryName, Toast.LENGTH_SHORT)
       .show();
    }
   } else {
    if (Math.abs(velocityX) < SWIPE_THRESHOLD_VELOCITY) {
     return false;
    }
    if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE) {
     Toast.makeText(DemoSwipe.this,
       "swipe RightToLeft " + countryName, 5000).show();
    } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE) {
     Toast.makeText(DemoSwipe.this,
       "swipe LeftToright  " + countryName, 5000).show();
    }
   }

   return super.onFling(e1, e2, velocityX, velocityY);

  }

  @Override
  public boolean onTouch(View v, MotionEvent event) {

   return gDetector.onTouchEvent(event);
  }

  public GestureDetector getDetector() {
   return gDetector;
  }

 }
}

>>>> To include Swipe  Event in our Activity we need a class which extends SimpleOnGestureListener and implements OnTouchListener  (SwipeGestureListener- in the above example). we need a constructor for this class and we need to @override the onFling(..),onTouch(..) events.Swipe event is controlled by OnFling() method. we can control LeftToRight ,RightToleft , BottomToTop, TopToBottom  swipe events using this.

@Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {

   final int position = lvCountry.pointToPosition(
     Math.round(e1.getX()), Math.round(e1.getY()));

   String countryName = (String) lvCountry.getItemAtPosition(position);

   if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
    if (Math.abs(e1.getX() - e2.getX()) > SWIPE_MAX_OFF_PATH
      || Math.abs(velocityY) < SWIPE_THRESHOLD_VELOCITY) {
     return false;
    }
    if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE) {
     Toast.makeText(DemoSwipe.this, "bottomToTop" + countryName,
       Toast.LENGTH_SHORT).show();
    } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE) {
     Toast.makeText(DemoSwipe.this,
       "topToBottom  " + countryName, Toast.LENGTH_SHORT)
       .show();
    }
   } else {
    if (Math.abs(velocityX) < SWIPE_THRESHOLD_VELOCITY) {
     return false;
    }
    if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE) {
     Toast.makeText(DemoSwipe.this,
       "swipe RightToLeft " + countryName, 5000).show();
    } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE) {
     Toast.makeText(DemoSwipe.this,
       "swipe LeftToright  " + countryName, 5000).show();
    }
   }

   return super.onFling(e1, e2, velocityX, velocityY);

  }

>>> then we need to create  instance of the  SwipeGestureListener
in our mainActivity (DemoSwipe - in the above Example) and set the instance to the onTochEvent of the ListView .



SwipeGestureListener gestureListener;
gestureListener = new SwipeGestureListener(DemoSwipe.this);
lvCountry.setOnTouchListener(gestureListener);


2. Main.xml file  is given below 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/LinearLayout1"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >


    <ListView

        android:id="@+id/lv_country"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" >

    </ListView>


</LinearLayout>

Comments

  1. are your files available for downlaod?

    ReplyDelete
  2. e1 is always null, I can't get rid of it quite a while, so jelly to see that it once worked

    ReplyDelete
  3. Great Demo Thanks

    How can i implement Click Event of Listview??

    ReplyDelete
  4. what is the use of SWIPE_THRESHOLD_VELOCITY = 200;

    ReplyDelete

Post a Comment

Popular posts

Android List View using Custom Adapter and SQLite

following is a simple applicaton to create ListView using  Custom adapter.screenshot of the application  is like this . ListView is not used in android Anymore . We use  RecyclerView  and  CardView   in Android RecyclerView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/04/android-recyclerview-example.html RecyclerView with Cardview Example is available on the following link http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html The ListView below the submit button is populated using Custom Adapter.Data is stored and retrieved using SQLite databsase. you can download the source code of this project from  google drive   https://drive.google.com/folderview?id=0BySLpWhqmbbdUXE5aTNhazludjQ&usp=sharing click on the above link ->sign into  your  google account ->add this to your google drive -> open it in google drive and download it. To create a simple application like this 1.  Create a class which extends  

Keytool is not recognized as internal or extenal command / Adding PATH in system variable

If you are running a keytool command  keytool -list -v -keystore C:\Users\arun\.android\debug.keystore -alias androiddebugkey -storepass android    and getting an error   'keytool' is not recognized as an internal or external command  If you are using any other commad like java,javac , etc.. and getting an error " is not recognized as an internal or external command"  you can also use this same steps  you are getting this error because keytool.exe , executable file which exists in the bin directory of your JDK  is not added to Path in your Environmental variables. To resolve this issue 1 .first we need to find the bin Directory of our jdk    Usually this will be in  C:\Program Files\Java\jre1.8.0_221\bin (jre1.8.0_221 - change this to your latest version , ). you can see keytool.exe file in the bin directory . (If you installed jdk in a different directory Find your Jdk installation folder and  use that path.) 2 . we need to add this bin directory

Simple Calculator With ViewModel and LIveData

This is a simple calculator with basic mathematical operations. You can download full source code of this project from Github https://github.com/arunkfedex/SimpleCalculator We are using ViewModel and LiveData so we need to add those dependencies in build.gradle file. build.gradle plugins { id 'com.android.application' id 'kotlin-android' } android { compileSdk 30 defaultConfig { applicationId "com.arun.androidtutsforu.simplecalculator" minSdk 21 targetSdk 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 ta