I am trying to create a Gesture Detector that will fire when the user swipes left or right. I am using a ViewPager, and have disabled the functionality to page between views by swiping left and right by the code:
mViewPager.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View arg0, MotionEvent arg1) {
return true;
}
});
I am trying to create an OnTouchListener within my fragment by using:
View v = inflater.inflate(R.layout.fragment_myview, null, false);
final GestureDetector gesture = new GestureDetector(getActivity(),
new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.i("fling", "onFling has been called!");
final int SWIPE_MIN_DISTANCE = 120;
try {
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE) {
Log.i("fling", "Right to Left");
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE) {
Log.i("fling", "Left to Right");
}
} catch (Exception e) {
// nothing
}
return super.onFling(e1, e2, velocityX, velocityY);
}
});
v.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gesture.onTouchEvent(event);
}
});
The LogCat shown here isn't getting fired, and I'm not sure why. Does anyone have any suggestions? Thanks in advance.
Change the code as below and try:
If you return true in onTouch function that means view pager has consumed the touch event. So touch event wont be called to the parent view, in your case its fragment view. So return false instead. This should work.