I have created an activity for monitoring the swiping of the screen to right and to left. Here is the code which I have implemented.
public class YourActivity extends Activity {
private GestureDetector gestureDetector;
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
gestureDetector = new GestureDetector(
new SwipeGestureDetector());
}
/* ... */
@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return super.onTouchEvent(event);
}
private void onLeftSwipe() {
// Here I have used a toast to check whether it's detectecting my swipe to left.
// But it is not working.
}
private void onRightSwipe() {
// Here I have used a toast to check whether it's detectecting my swipe to right.
// But it is not working.
}
// Private class for gestures
private class SwipeGestureDetector
extends SimpleOnGestureListener {
// Swipe properties, you can change it to make the swipe
// longer or shorter and speed
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 200;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
try {
float diffAbs = Math.abs(e1.getY() - e2.getY());
float diff = e1.getX() - e2.getX();
if (diffAbs > SWIPE_MAX_OFF_PATH)
return false;
// Left swipe
if (diff > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
YourActivity.this.onLeftSwipe();
// Right swipe
} else if (-diff > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
YourActivity.this.onRightSwipe();
}
} catch (Exception e) {
Log.e("YourActivity", "Error on gestures");
}
return false;
}
}
}
When I run this code, nothing happenend while I swiped to left or even to right. The toasts at onRightSwipe() and onLeftSwipe didn't work at all. Can someone correct me if I'm wrong anywhere in my code. Thanks in advance for your help..
EDIT:: The above code works fine if there are no textviews in my activity layout xml page. But if there is some textviews and try to settext the values during runtime, then my app force closes, and error is shown as java.lang.nullpointerexception. What wrong did I do here??