在启动器应用程序上向上和向下滑动手势

问题描述 投票:0回答:1

我正在开发 Android 启动器应用程序,但我无法在主屏幕上使用向上和向下滑动手势。我正在使用 RecyclerView 在网格布局中显示应用程序。

在主屏幕上,如果我向上滑动,它应该打开“所有应用程序片段”,在所有应用程序屏幕上,如果我向下滑动,它应该关闭它。我无法让任何听众实现这种行为。

我想在整个屏幕上而不是在recyclerView上实现此行为。非常友善的解决方案,无论 recyclerView 如何,滑动手势都可以工作。

我尝试过 onTouchListner 但由于 RecyclerView,它不起作用。

滑动手势应该适用于整个主屏幕。

android kotlin android-recyclerview gesture android-launcher
1个回答
0
投票

要实现此行为,您可以做的是创建一个实现 View.OnTouchListener 的新类,添加 GestureDetector 并重写 onFling 方法来检测向上滑动和向下滑动手势。之后,您可以将这个新的 touchListener 添加到 onCreate 中的片段视图中,并根据需要重写 onSwipeUp() 和 onSwipeDows() 方法。 touchListener 类应该如下所示

public class OnSwipeTouchListener implements View.OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context context) {
        gestureDetector = new GestureDetector(context, new GestureListener());
    }

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

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(@NonNull MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            float diffY = e2.getY() - e1.getY();
            float diffX = e2.getX() - e1.getX();

            if (Math.abs(diffY) > Math.abs(diffX)) {
                if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeDown();
                    } else {
                        onSwipeUp();
                    }
                    return true;
                }
            }
            return false;
        }
    }

    public void onSwipeDown() {
    }

    public void onSwipeUp() {
    }
}

然后将其添加到片段的 onCreate 方法中的视图中

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        // Initialize your app dock here

        view.setOnTouchListener(new OnSwipeTouchListener(requireContext()) {
            @Override
            public void onSwipeUp() {
                openAppListFragment();
            }
        });

        return view;
    }
© www.soinside.com 2019 - 2024. All rights reserved.