请注意,
onInterceptTouchEvent()是ViewGroup类中的方法,而不是来自Activity.
您可以通过将逻辑从onInterceptTouchEvent()移动到dispatchTouchEvent(MotionEvent ev)来实现所需的行为.请记住调用dispatchTouchEvent(MotionEvent ev)的超类实现来处理应该正常处理的事件.
另请注意,只有在delta大于system constant for touch slop时才应考虑移动.我建议用户通过测试yDelta / 2>确保用户正在按照您想要的方向滑动. xDelta而不是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);
}
}