Android如何实现整个RecyclerView的左右滑动手势检测
问题:如何实现整个RecyclerView视图的稳定左右滑动检测
- 已查阅到大量针对RecyclerView列表项的滑动检测实现示例,但当前需求是检测整个RecyclerView视图层面的左右滑动手势,和单列表项滑动检测的场景存在本质区别。
- 已有普通视图滑动方案适配失效:目前也有不少讲解如何在布局容器等普通视图上实现左右滑动检测的参考方案,但将对应的触摸监听器绑定到RecyclerView上后完全无法生效。
已尝试方案的异常记录
SmartSwipe第三方滑动库适配问题
尝试接入SmartSwipe第三方滑动库,该库的滑动视觉效果符合预期,但接入时存在两类异常:
- 用库的API包裹RecyclerView实现滑动效果时,仅显示滑动动画,看不到RecyclerView的原有列表数据,对应实现代码如下:
SmartSwipe.wrap(binding.recyclerView).addConsumer(BezierBackConsumer()) .enableHorizontal() .addListener(object : SimpleSwipeListener() { override fun onSwipeOpened(wrapper: SmartSwipeWrapper, consumer: SwipeConsumer, direction: Int) { } }) - 若将库的滑动绑定逻辑绑定到RecyclerView的外层ConstraintLayout容器上,完全没有任何响应效果。
自定义触摸监听方案问题
尝试给RecyclerView绑定自定义OnTouchListener实现滑动检测,过程出现两类问题:
- 基础实现版本绑定到RecyclerView时会抛出空指针异常,对应实现代码如下:
报错日志如下:view.setOnTouchListener(object : OnHorizontalSwipeListener(requireContext()) { override fun onRightSwipe() { println("Swipe right") } override fun onLeftSwipe() { println("Swipe left") } })E/MessageQueue-JNI: java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter e1 at ui.OnHorizontalSwipeListener$GestureListener.onFling(Unknown Source:2) - 按照报错提示给监听器的
onFling方法增加入参空值判断后,功能存在稳定性缺陷:只有当RecyclerView被滚动过几次之后,滑动检测才会生效;在刚初始化完成的Fragment上尝试左右滑动时,检测逻辑完全没有响应。对应修改后的代码片段:override fun onFling( e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float ): Boolean { var result = false try { if (e1 != null && e2 != null) { val diffY = e2.y - e1.y val diffX = e2.x - e1.x
内容的提问来源于stack exchange,提问作者Mirco
相关产品推荐
相关产品推荐

