I'm trying to implement a swipe gesture in my app. I've made almost all code but it doesn't work.
Here is the code I have in my Activity:
// Swipe detector
gestureDetector = new GestureDetector(new SwipeGesture(this));
gestureListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event)
{
Log.e("", "It works");
return gestureDetector.onTouchEvent(event);
}
};
LinearLayout root = (LinearLayout) findViewById(R.id.rules_root);
root.setOnTouchListener(gestureListener);
When I touch the screen, the logcat displays it works
.
Here he my the code of the class SwipeGesture
:
public class SwipeGesture extends SimpleOnGestureListener
{
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private Activity activity;
public SwipeGesture(Activity activity)
{
super();
this.activity = activity;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
Log.e("", "Here I am");
try
{
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false;
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
if ( ((TabActivity) activity.getParent()).getTabHost() != null )
{
TabHost th = ((TabActivity) activity.getParent()).getTabHost();
th.setCurrentTab(th.getCurrentTab() - 1);
}
else
{
activity.finish();
}
Log.e("", "Swipe left");
}
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
{
if ( ((TabActivity) activity.getParent()).getTabHost() != null )
{
TabHost th = ((TabActivity) activity.getParent()).getTabHost();
th.setCurrentTab(th.getCurrentTab() + 1);
}
Log.e("", "Swipe right");
}
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
}
The line Log.e("", "Here I am");
is never displayed. So I presume the onFling method is never called.
Any ideas of why this doesn't work?
Thanks.
Regards.
V.
In your SimpleOnGestureListener, override onDown for your gestures to register. It can just return true but it has to be defined like this..
....See this link.. and the comment below the answer..
You need to change a couple of things, here's an example.
Set your OnTouchListener:
SwipeGesture class:
It looks like you're swiping between
Tabs
. UsingFragments
andViewPager
is much easier and smoother for your users.