Handling Touch Events - onInterceptTouchEvent and onTouchEvent
Note that onInterceptTouchEvent()
is a method from the ViewGroup
class, and not from Activity
.
You can achieve the desired behavior by moving your logic from onInterceptTouchEvent()
to dispatchTouchEvent(MotionEvent ev)
. Remember to call the superclass implementation of dispatchTouchEvent(MotionEvent ev)
to handle the events that should be handled normally.
Also note that you should consider a movement to be a swipe only when the delta is bigger than the system constant for touch slop. And I suggest making sure that the user is swiping in the direction you want by testing yDelta / 2 > xDelta
instead of yDelta > xDelta
.
public class Game extends Activity {
private int mSlop;
private float mDownX;
private float mDownY;
private boolean mSwiping;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_activity);
ViewConfiguration vc = ViewConfiguration.get(this)
mSlop = vc.getScaledTouchSlop();
//other code....
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getX();
mDownY = ev.getY();
mSwiping = false;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if(mSwiping) {
swipeScreen(); //if action recognized as swipe then swipe
}
break;
case MotionEvent.ACTION_MOVE:
float x = ev.getX();
float y = ev.getY();
float xDelta = Math.abs(x - mDownX);
float yDelta = Math.abs(y - mDownY);
if (yDelta > mSlop && yDelta / 2 > xDelta) {
mSwiping = true;
return true;
}
break;
}
return super.dispatchTouchEvent(ev);
}
}