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> x1it means Left to Right sweep has been performed and if x2<x1it 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 andif y2<y1it means Down to UP sweep has been performed

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 linesdiffx = 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))

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