ScrollView内嵌RecyclerView如何禁用滚动且显示全部子项?
解决方案
方案一:使用自定义非滚动LinearLayoutManager(推荐)
默认的LinearLayoutManager对wrap_content属性的测量逻辑只会计算可见区域的子项高度,所以即便关闭嵌套滚动也会出现内容显示不全的问题,你可以重写LayoutManager的测量逻辑适配需求:
- 自定义LinearLayoutManager
Kotlin实现:
class NonScrollLinearLayoutManager(context: Context) : LinearLayoutManager(context) { override fun onMeasure(recycler: RecyclerView.Recycler, state: RecyclerView.State, widthSpec: Int, heightSpec: Int) { // 取消高度测量限制,计算所有子项总高度 val expandHeightSpec = View.MeasureSpec.makeMeasureSpec(Int.MAX_VALUE shr 2, View.MeasureSpec.AT_MOST) super.onMeasure(recycler, state, widthSpec, expandHeightSpec) } }
Java实现:
public class NonScrollLinearLayoutManager extends LinearLayoutManager { public NonScrollLinearLayoutManager(Context context) { super(context); } @Override public void onMeasure(@NonNull RecyclerView.Recycler recycler, @NonNull RecyclerView.State state, int widthSpec, int heightSpec) { int expandHeightSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST); super.onMeasure(recycler, state, widthSpec, expandHeightSpec); } }
- 给RecyclerView设置自定义LayoutManager,同时保留关闭嵌套滚动的配置:
Kotlin代码:
recyclerview2.apply { layoutManager = NonScrollLinearLayoutManager(this@YourActivity) isNestedScrollingEnabled = false }
Java代码:
recyclerview2.setLayoutManager(new NonScrollLinearLayoutManager(this)); recyclerview2.setNestedScrollingEnabled(false);
方案二:动态计算总高度(仅适用于子项高度固定的场景)
如果所有RecyclerView子项高度统一,你也可以在Adapter设置完成后手动计算总高度,赋值给RecyclerView的布局参数:
// 示例:单个子项高度为100dp,先转换为像素值 val itemHeightPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100f, resources.displayMetrics).toInt() val itemCount = recyclerview2.adapter?.itemCount ?: 0 // 若存在分割线,需要额外加上分割线总高度 // val dividerHeightPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1f, resources.displayMetrics).toInt() // val totalHeight = itemHeightPx * itemCount + (itemCount - 1) * dividerHeightPx val totalHeight = itemHeightPx * itemCount recyclerview2.layoutParams = recyclerview2.layoutParams.apply { height = totalHeight }
优化建议
你可以将外层的ScrollView替换为NestedScrollView,对嵌套滚动的兼容性更好,避免出现滑动卡顿、事件冲突等小问题,无需额外修改其他逻辑。
内容的提问来源于stack exchange,提问作者Darksymphony
相关产品推荐
相关产品推荐

