You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestedScrollView内RecyclerView的SelectionTracker拖拽选中功能失效问题

问题描述

预期行为

长按通过SelectionTracker启动选择模式,拖拽可选中更多列表条目。

实际行为

仅能选中单个条目,后续NestedScrollView会拦截触摸事件,拖拽选中功能失效,同时出现过度滚动拉伸效果。

布局结构(自上而下)

  • CoordinatorLayout(包含AppBarLayout)
  • ViewPager2
  • NestedScrollView(因ViewPager2要求必须添加)
  • RecyclerView(已设置android:nestedScrollingEnabled="false")

解决方案

核心思路是让NestedScrollView在SelectionTracker处于选择模式时,放弃触摸事件拦截权,将事件交由RecyclerView处理。

1. 自定义NestedScrollView重写拦截逻辑

创建自定义子类,添加开关控制触摸拦截状态:

class InterceptableNestedScrollView(context: Context, attrs: AttributeSet?) : NestedScrollView(context, attrs) {
    var shouldInterceptTouch = true

    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        return if (!shouldInterceptTouch) {
            false
        } else {
            super.onInterceptTouchEvent(ev)
        }
    }
}

2. 关联SelectionTracker状态变化

在Fragment/Activity中监听选择模式切换,同步更新NestedScrollView的拦截状态:

selectionTracker.addObserver(object : SelectionTracker.SelectionObserver<Long>() {
    override fun onSelectionChanged() {
        super.onSelectionChanged()
        val isInSelectionMode = selectionTracker.hasSelection()
        yourCustomNestedScrollView.shouldInterceptTouch = !isInSelectionMode
    }
})

3. 替换布局中的NestedScrollView

将原布局里的NestedScrollView替换为自定义类:

<com.yourpackage.InterceptableNestedScrollView
    android:id="@+id/custom_nested_scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- 内部RecyclerView等布局 -->
</com.yourpackage.InterceptableNestedScrollView>

额外优化

若拖拽时仍有滚动干扰,可在选择模式下直接禁用NestedScrollView的滚动功能:

override fun onSelectionChanged() {
    super.onSelectionChanged()
    val isInSelectionMode = selectionTracker.hasSelection()
    yourCustomNestedScrollView.shouldInterceptTouch = !isInSelectionMode
    yourCustomNestedScrollView.isEnabled = !isInSelectionMode
}

内容的提问来源于stack exchange,提问作者Remc4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:19:59