Friday, June 21, 2013

Detecting Swipe Event In Android

To detect Touch Event and other events like Left to Right sweep and Right to Left sweep, we use  MotionEvent  class.

MotionEvent


MotionEvent object is used to report movement (mouse, pen, finger, trackball) events. Motion events may hold either absolute or relative movements and other data, depending on the type of device.

Motion events describe movements in terms of an action code and a set of axis values. The action code specifies the state change that occurred such as a pointer going down or up. The axis values describe the position and other movement properties.

For example, when the user first touches the screen, the system delivers a touch event to the appropriate View with the action code ACTION_DOWN and a set of axis values that include the X and Y coordinates of the touch and information about the pressure, size and orientation of the contact area.


In the code below I have described with proper Source Code about detecting Swap Events but first we should understand the basics.

onTouchEvent () method ogets called when User performs any touch event on screen

when a User swaps from Left to Right or Right to left

user first touches on the screen ( lets say first x coordinate is x1) holds ,swaps  then leaves the screen  (lets say second x coordinate is x2)

so if x2> x1  it means Left to Right sweep has been performed and
     if x2<x1   it means Right to Left sweep has been performed

Similarly we can track UP to Down and Down to UP swap

if  y2> y1  it means UP to Down sweep has been performed and
if  y2<y1   it means Down to UP sweep has been performed

Example with Source Code


main.xml


TouchEvent



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

        <TextView
            android:layout_marginTop="80dp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:gravity="center"
            android:textColor="#000099"
            android:textSize="30dp"
            android:text="Detect Swap Event Demo" />
       
   
</LinearLayout>




MainActivity.java


public class MainActivity extends Activity
{
            float x1,x2;
            float y1, y2;
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.main);
            }
          
            //
onTouchEvent () method gets called when User performs any touch event on screen 
           // Method to handle touch event like left to right swap and right to left swap
                        public boolean onTouchEvent(MotionEvent touchevent)
                        {
                                     switch (touchevent.getAction())
                                     {
                                            // when user first touches the screen we get x and y coordinate
                                             case MotionEvent.ACTION_DOWN:
                                             {
                                                 x1 = touchevent.getX();
                                                 y1 = touchevent.getY();
                                                 break;
                                            }
                                             case MotionEvent.ACTION_UP:
                                             {
                                                 x2 = touchevent.getX();
                                                 y2 = touchevent.getY(); 


                                                 / /if left to right
sweep event on screen
                                                 if (x1 < x2)
                                                 {
                                                     Toast.makeText(this, "Left to Right Swap Performed", Toast.LENGTH_LONG).show();
                                                  }
                                               
                                                 // if right to left sweep event on screen

                                                 if (x1 > x2)
                                                 {
                                                     Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();
                                                 }
                                               
                                                 // if UP to Down
sweep event on screen
                                                 if (y1 < y2)
                                                 {
                                                     Toast.makeText(this, "UP to Down Swap Performed", Toast.LENGTH_LONG).show();
                                                 }
                                               
                                                 / /if Down to UP
sweep event on screen
                                                 if (y1 > y2)
                                                 {
                                                     Toast.makeText(this, "Down to UP Swap Performed", Toast.LENGTH_LONG).show();
                                                  }
                                                 break;
                                             }
                                     }
                                     return false;
                        }

  
}





TouchEvent




42 comments:

  1. thanks very simple and good example

    ReplyDelete
  2. Very Good Example Sir But How Do You Do It Using A Image i.e., Sliding a Image and Viewing A Text ??/

    ReplyDelete
  3. Good But How To Swipe With A Image To Top To Display Something ??? Please Help Out !!!

    ReplyDelete
  4. It's simple but sometimes left-right swap and down-up swap both performs, tell me why?

    ReplyDelete
    Replies
    1. If the user doesn't swipe exactly left to right (y1=y2) or up to down (x1=x2) then both events are detected. To solve this compare the difference of the x values with the difference of the y values. A greater difference between the x values means a left to right swipe. In the code add two float variables after the float y1,y2;
      float diffx, diffy;
      Right before the first if statement include the lines
      diffx = x2-x1;
      diffy = y2-y1;
      Within the if statements add as follows:
      if (x1 < x2 && Math.abs(diffy) < Math.abs(diffx))
      if (x2 < x1 && Math.abs(diffy) < Math.abs(diffx))
      if (y1 < y2 && Math.abs(diffx) < Math.abs(diffy))
      if (y2 < y1 && Math.abs(diffy) < Math.abs(diffx))

      Delete
    2. Hi sir how exactly are we going to add the if statements? could you please provide a sample. thank you

      Delete
    3. down to up dosen't work....when i include above code... and left to right n down to up both work on same time...give a solution..thanks in advance

      Delete
  5. Very clear tutorial, I want to ask though.. here we check up and down left and right if we want diagonal we just combine the up and left for example?

    ReplyDelete
  6. Very good example, but if we want to check diagonal? we just combine for example the up and left at the same time?

    ReplyDelete
  7. that's very good example but tost is running which not required at one action also perform downup and updaown in this example.........

    ReplyDelete
  8. Great tutorial with clear explanation.

    ReplyDelete
  9. Simple is best, Thank you.

    ReplyDelete
  10. how can we get on click () including this all...

    ReplyDelete
  11. i want to handle onclick on listitem too,among these all events... how can i do that

    ReplyDelete
  12. Thank you, very simple, very clear.

    ReplyDelete
  13. Thank you, very simple, very clear.

    ReplyDelete
  14. very simple and clear.. thanks alot and keep it up

    ReplyDelete
  15. good example... bt what if we wnt to swipe to another page? how can we do this?

    ReplyDelete
  16. If i want to just swipe horiztonally, how do I accomplish this? I tried to disable "y" but it still allows swipe vertically.

    ReplyDelete
  17. Thanks ! That's great.

    ReplyDelete
  18. How can i enable scrolling Y axis with this code?

    ReplyDelete
  19. Hello,
    if (x1 > x2)
    {
    Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();
    How to change TextView
    }

    ReplyDelete
    Replies
    1. First give id to TextView of Detect Swap Event Demo in main.xml
      and then
      if (x1 > x2)
      {
      Toast.makeText(this, "Right to Left Swap Performed", Toast.LENGTH_LONG).show();
      // to change TextView
      TextView tv = (TextView) findViewById(R.id.textView1);
      tv.setText("It has now Moved to Right");
      }

      Delete
    2. Glad to see fuuastians reply :) (Y)

      Delete
  20. Very Helpful for beginners!!

    ReplyDelete
  21. nice bro!
    its work fine here.

    thank you!

    ReplyDelete
  22. very nice sir,thank you so much!!!

    ReplyDelete
  23. Thanks it help us very much

    ReplyDelete
  24. Thaks A LOT. It REALLY helps me.

    ReplyDelete
  25. thaaaaaanks alooooot
    i searched for this method about one weak but i didnt find any thing
    thank you very much

    ReplyDelete
  26. Really nice,clear explanation got..,Thanks

    ReplyDelete
  27. Really nice,clear explanation,simple code,thanks

    ReplyDelete