我有一个包含单个片段的Activity:
getFragmentManager().beginTransaction().add(android.R.id.content,fragment1).commit();
我的问题是,我如何检测手势?我尝试使用OnTouchListener,也使用onInterceptTouchEvent方法.基本上我想检测滑动.我的SwipeGestureDetector看起来像这样:
public class SwipeGestureDetector extends SimpleOnGestureListener { // ... @Override public boolean onDown(MotionEvent e) { return true; } public boolean onFling(MotionEvent e1,MotionEvent e2,float veLocityX,float veLocityY) { 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) { // right to left swipe } else if (e2.getX() - e1.getX() > SWIPE_MIN_disTANCE && Math.abs(veLocityX) > SWIPE_THRESHOLD_VELociTY) { // left to right swipe } } catch (Exception e) { // nothing } return false; } }
然后我在我的活动中注册它:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // .. SwipeGestureDetector swipeDetector = new SwipeGestureDetector(); final GestureDetector detector = new GestureDetector(this,swipeDetector); findViewById(android.R.id.content).setonTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v,MotionEvent event) { return detector.onTouchEvent(event); } }); }
不幸的是,没有检测到滑动手势.我怎样才能做到这一点?请不要建议使用ViewPager,我不能使用它.
解决方法
这是我为这个问题做的解决方法.
我不得不在我的Activity中覆盖dispatchTouchEvent()方法.当窗口发生触摸事件时调用此方法.
@Override public boolean dispatchTouchEvent(MotionEvent ev) { boolean handled = swipeDetector.onTouchEvent(ev); if (!handled) { return super.dispatchTouchEvent(ev); } return handled; }