使用手势更改片段

Change fragment with Gesture

我正在尝试使用手势来更改 MainActivity 中的 Fragment。

我用这个代码。

主要 Activity :

public class MainActivity extends FragmentActivity {

/* ... */

HomeGestureDetector homeGestureDetector = new HomeGestureDetector(MainActivity.this){
        public void onSwipeRight() {
            menuListener((selectedItem-1 == -1)? 4 : selectedItem-1) ;
        }
        public void onSwipeLeft() {
            menuListener((selectedItem + 1) % 5);
        }
    };
    center.setOnTouchListener(new GestureManager(new GestureDetector(MainActivity.this, homeGestureDetector)));
}

手势管理器:

public class GestureManager implements OnTouchListener {

private final GestureDetector gestureDetector;

public GestureManager(GestureDetector gd) {
    gestureDetector = gd;
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

最后,HomeGestureDetector 是扩展 SimpleOnGestureListener 的 class,但就像您可以看到方法 onSwipeRight() onSwipeLeft() 的实现是 MainActivity.

中的委托

最初这段代码工作正常,但是当我用其他元素填充布局时,似乎无法拦截手势,因为侦听器位于容器布局上,当我点击时显然我触摸了包含的元素,而不是容器。

如何实现此功能?

考虑使用 ViewPager 修改您的实现。

ViewPager 是...

Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows.

(来自docs

Interesting/Required 阅读以获取(我会 post 代码但 developer.android.com 已经得到 一切 你需要的):

https://developer.android.com/training/implementing-navigation/lateral.html#horizontal-paging

  • 本文档将帮助您在代码库中设置 ViewPager

https://developer.android.com/training/implementing-navigation/lateral.html#swipe-tabs

  • 这部分将帮助您改变您的 MainActivity#menuListener 方法

https://developer.android.com/design/patterns/swipe-views.html

  • 这将有助于理解关于有效使用用户习惯的 ViewPager 的 android 指南

嗯!