getItemCount正常但RecyclerView的onCreateViewHolder与onBindViewHolder未调用如何解决
问题根因排查
- 主布局的RecyclerView尺寸配置错误
activity_travel_view_list.xml中RecyclerView直接作为根布局,宽高都设置为0dp,没有任何约束规则,控件实际渲染尺寸为0,系统不会触发条目绘制逻辑,因此onCreateViewHolder、onBindViewHolder不会被调用,只有getItemCount会被适配器初始化时调用一次。 - 列表项布局高度配置错误
travel_view.xml中根布局高度设置为match_parent,单个条目就会占满整个RecyclerView,后续条目无法显示。
修复方案
1. 修改主布局activity_travel_view_list.xml
将RecyclerView的宽高改为match_parent即可,修改后代码:
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/travelListView" android:visibility="visible"> </androidx.recyclerview.widget.RecyclerView>
如果后续需要将RecyclerView放在ConstraintLayout中使用0dp配置,补充对应上下左右的约束属性即可。
2. 修改列表项布局travel_view.xml
将根LinearLayout的高度改为wrap_content,可额外增加底部padding优化列表显示效果,修改后代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="10dp" android:paddingTop="10dp" android:paddingBottom="10dp"> <TextView android:id="@+id/tripName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:textSize="34sp"></TextView> <TextView android:id="@+id/tripDetails" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:textSize="16sp"></TextView> </LinearLayout>
可选优化
在给RecyclerView设置适配器后新增一行travelList.getAdapter().notifyDataSetChanged(),保证数据变更后列表可以正常刷新。
内容的提问来源于stack exchange,提问作者Karthik Prakash
相关产品推荐
相关产品推荐

