Android ListView嵌套NestedScrollView仅显示6个条目问题排查求助
问题核心原因
你遇到的是Android滚动组件嵌套的典型冲突:ListView本身自带滚动能力,外层的NestedScrollView也具备滚动能力,两者嵌套时系统无法正确测量ListView的完整高度,仅能计算出当前屏幕可见区域的高度,因此只会渲染部分条目,最后一个条目还会被截断。
解决方案(按优先级从高到低排列)
1. 最优方案:移除外层NestedScrollView
直接让ListView作为CoordinatorLayout的直接子组件,配置滚动行为即可,既保留ListView的条目复用性能,又能和顶部的折叠工具栏正常联动:
<!-- 删除原有的NestedScrollView节点,直接添加如下ListView配置 --> <ListView android:id="@+id/similar_list" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:listitem="@layout/items_similar" />
2. 次优方案:替换为RecyclerView
如果需要在列表上方添加其他非列表内容,保留NestedScrollView的前提下,将ListView替换为RecyclerView,关闭嵌套滚动即可:
<androidx.recyclerview.widget.RecyclerView android:id="@+id/similar_list" android:layout_width="match_parent" android:layout_height="match_parent" android:nestedScrollingEnabled="false" tools:listitem="@layout/items_similar" />
3. 兼容方案:自定义不可滚动的ListView
如果必须保留NestedScrollView和ListView的组合,可自定义ListView重写测量逻辑,强制计算所有条目的总高度:
public class NonScrollListView extends ListView { public NonScrollListView(Context context) { super(context); } public NonScrollListView(Context context, AttributeSet attrs) { super(context, attrs); } public NonScrollListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
之后将布局中的ListView替换为自定义的NonScrollListView即可。
注意:方案2和3会导致列表所有条目一次性渲染,失去视图复用机制,条目数量较多时会出现性能下降,仅适合条目数量较少的场景使用。
内容的提问来源于stack exchange,提问作者EduSantino
相关产品推荐
相关产品推荐

