Tuesday 8 January 2013

Gesture example in Android

Gestures allow users to interact with your app by manipulating the screen objects you provide. There is  some type of Gesture used by User to interact to your application

         Type of Gesture                                                          Action 
  1. Touch                      -------------------------------------   press, lift 
  2. Long Press            ---------------------------------    Press, wait, lift
  3. Swipe                     ------------------------------    Press, lift, move 
  4. Drag                                            " "         Long press, move, lift
  5. Double Touch                            " "    Two touches in quick succession
  6. Pinch open                             " "  2-finger press, move outwards, lift
  7. Pinch Close                           " "2-finger press, move inwards, lift
    This the 7 type gesture in Android . For more detail follow this link.         
              

 1. The Touch event is the simple  gesture event  in android. As foe example button click in your app is Touch gesture example. So You have to use clickListner method in android to handle this event for your touch functionality  As for example when  user click/touch on Button(say Login) then You have to listen it and performed needed task.   

2. Long press:-    This is also a touch event and generally used in list view in android . When user click/touch and hold an item from list view then we have to listen this event and open a pop type window. in that window we have to perform some task like Delete, Detail, Copy, paste etc. 
    To listen this event we use this method
list.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                final int arg2, long arg3) {

}
}
 Here list is List View reference. 
3. Swipe :- This is a gesture event for left , right, top  and down movement of touch event by user. You have to detect user movement and based upon that you have to perform required action. For this we have to use SimpleOnGestureListener class in android. it is A convenience class to extend when you only want to listen for a subset of all the gestures i.e up, down, left right motion of user. 
Creating a project  for Swipe Gesture 
Create a new Android project and named it GestureApp. By default you get MainActiviuty.java  put the following code inside that 
public class MainActivity extends Activity implements SimpleGestureListener {

private SimpleGestureFilter detector;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    detector = new SimpleGestureFilter(this,this);
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    // TODO Auto-generated method stub
       this.detector.onTouchEvent(ev);
       return super.dispatchTouchEvent(ev);
}

@Override
public void onSwipe(int direction) {
    // TODO Auto-generated method stub
    String str = "";

      switch (direction) {

      case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
                                                  newPages();
                                               break;
      case SimpleGestureFilter.SWIPE_LEFT :  str = "Swipe Left";
                                                    newPages();
                                                     break;
      case SimpleGestureFilter.SWIPE_DOWN :  str = "Swipe Down";
                                                    newPages();
                                                     break;
      case SimpleGestureFilter.SWIPE_UP :    str = "Swipe Up";
                                                     newPages();
                                                     break;

      } 
       Toast.makeText(this, str, Toast.LENGTH_SHORT).show();

}

private void newPages() {
     Intent intent  = new Intent(getBaseContext(), Welcome.class);
    startActivity(intent);

}

@Override
public void onDoubleTap() {
    // TODO Auto-generated method stub
     Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
     //Double touch

}}
Now create a new class inside a src and named it as SimpleGestureFilter and put following code in it.
public class SimpleGestureFilter extends SimpleOnGestureListener{

public final static int SWIPE_UP    = 1;
 public final static int SWIPE_DOWN  = 2;
 public final static int SWIPE_LEFT  = 3;
 public final static int SWIPE_RIGHT = 4;

 public final static int MODE_TRANSPARENT = 0;
 public final static int MODE_SOLID       = 1;
 public final static int MODE_DYNAMIC     = 2;

 private final static int ACTION_FAKE = -13; //just an unlikely number
 private int swipe_Min_Distance = 100;
 private int swipe_Max_Distance = 200;
 private int swipe_Min_Velocity = 100;

 private int mode  = MODE_DYNAMIC;
 private boolean running = true;
 private boolean tapIndicator = false;

 private Activity context;
 private GestureDetector detector;
 private SimpleGestureListener listener;


 public SimpleGestureFilter(Activity context,SimpleGestureListener sgl) {

  this.context = context;
  this.detector = new GestureDetector(context, this);
  this.listener = sgl; 
 }

 public void onTouchEvent(MotionEvent event){

   if(!this.running)
  return;  

   boolean result = this.detector.onTouchEvent(event); 

   if(this.mode == MODE_SOLID)
    event.setAction(MotionEvent.ACTION_CANCEL);
   else if (this.mode == MODE_DYNAMIC) {

     if(event.getAction() == ACTION_FAKE) 
       event.setAction(MotionEvent.ACTION_UP);
     else if (result)
       event.setAction(MotionEvent.ACTION_CANCEL); 
     else if(this.tapIndicator){
      event.setAction(MotionEvent.ACTION_DOWN);
      this.tapIndicator = false;
     }

   }
   //else just do nothing, it's Transparent
 }

 public void setMode(int m){
  this.mode = m;
 }

 public int getMode(){
  return this.mode;
 }

 public void setEnabled(boolean status){
  this.running = status;
 }

 public void setSwipeMaxDistance(int distance){
  this.swipe_Max_Distance = distance;
 }

 public void setSwipeMinDistance(int distance){
  this.swipe_Min_Distance = distance;
 }

 public void setSwipeMinVelocity(int distance){
  this.swipe_Min_Velocity = distance;
 }

 public int getSwipeMaxDistance(){
  return this.swipe_Max_Distance;
 }

 public int getSwipeMinDistance(){
  return this.swipe_Min_Distance;
 }

 public int getSwipeMinVelocity(){
  return this.swipe_Min_Velocity;
 }


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

  final float xDistance = Math.abs(e1.getX() - e2.getX());
  final float yDistance = Math.abs(e1.getY() - e2.getY());

  if(xDistance > this.swipe_Max_Distance || yDistance > this.swipe_Max_Distance)
   return false;

  velocityX = Math.abs(velocityX);
  velocityY = Math.abs(velocityY);
        boolean result = false;

  if(velocityX > this.swipe_Min_Velocity && xDistance > this.swipe_Min_Distance){
   if(e1.getX() > e2.getX()) // right to left
    this.listener.onSwipe(SWIPE_LEFT);
   else
    this.listener.onSwipe(SWIPE_RIGHT);

   result = true;
  }
  else if(velocityY > this.swipe_Min_Velocity && yDistance > this.swipe_Min_Distance){
   if(e1.getY() > e2.getY()) // bottom to up 
    this.listener.onSwipe(SWIPE_UP);
   else
    this.listener.onSwipe(SWIPE_DOWN);

   result = true;
  }

   return result;
 }

 @Override
 public boolean onSingleTapUp(MotionEvent e) {
  this.tapIndicator = true;
  return false;
 }

 @Override
 public boolean onDoubleTap(MotionEvent arg0) {
  this.listener.onDoubleTap();;
  return true;
 }

 @Override
 public boolean onDoubleTapEvent(MotionEvent arg0) {
  return true;
 }

 @Override
 public boolean onSingleTapConfirmed(MotionEvent arg0) {

  if(this.mode == MODE_DYNAMIC){        // we owe an ACTION_UP, so we fake an       
     arg0.setAction(ACTION_FAKE);      //action which will be converted to an ACTION_UP later.                                    
     this.context.dispatchTouchEvent(arg0);  
  }   

  return false;
 }


    static interface SimpleGestureListener{
     void onSwipe(int direction);
     void onDoubleTap();
 }}
Lastly create a welcome.java class inside src folder of your project and put following code in it
public class Welcome extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.welcome);
} }
Now open your layout folder and create a simple welcome.xml file in it like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffccff"
    android:orientation="vertical" >
    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center"
        android:text="Welcome saurabh"
        android:textSize="18dp"/>

</LinearLayout>
Finally your manifest looks like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="yourApppackageName.com"
android:versionCode="1"
android:versionName="1.0" >

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

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Welcome"/>
</application>
All is well now your GestureApp is ready for launch. Now run it on Emulator or on real device and find the magic of  Swipe Gesture of Android 
      Happy Coding !!!

3 comments:

  1. Hi Saurabh,

    I have implemented the above code, but i am able to move to another activity at some certain swipe point only. I want to move to another activity if i swipe anywhere in the screen.

    Shyam

    ReplyDelete
  2. use these values, it is working.
    private int swipe_Min_Distance = 300;
    private int swipe_Max_Distance = 900;
    private int swipe_Min_Velocity = 100;

    ReplyDelete

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...