NestedScrollView内RecyclerView的SelectionTracker拖拽选中功能失效问题
问题描述
预期行为
长按通过SelectionTracker启动选择模式,拖拽可选中更多列表条目。
实际行为
仅能选中单个条目,后续NestedScrollView会拦截触摸事件,拖拽选中功能失效,同时出现过度滚动拉伸效果。
布局结构(自上而下)
CoordinatorLayout(包含AppBarLayout)ViewPager2NestedScrollView(因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
相关产品推荐
相关产品推荐

