RecyclerView.onBindViewHolder始终仅显示位置0数据问题求助
问题排查与修复方案
我帮你梳理了代码里的关键问题,正是这些问题导致RecyclerView只显示第0项内容:
1. getItemViewType方法中游标移动逻辑错误
你在getItemViewType里已经调用了cursor.moveToPosition(position)定位到目标位置,但紧接着又多写了一行cursor.move(position);——这个方法是让游标从当前位置再往后偏移position步,直接导致后续所有的游标位置完全错乱,后面的item根本取不到对应的数据,自然无法渲染显示。
修复后的getItemViewType:
@Override public int getItemViewType(int position) { if (cursor.moveToPosition(position)) { // 移除错误的cursor.move(position); String content = cursor.getString(cursor.getColumnIndex(DatabaseHandler.KEY_CONTENT)); int completed = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_COMPLETED)); int hightlight = cursor.getInt(cursor.getColumnIndex(DatabaseHandler.KEY_HIGHTLIGHT)); if (completed == 1) { if (hightlight == 1) { return HIGHTLIGHT_COMPETED; } return COMPLETED; } if (hightlight == 1 && completed == 0) { return HIGHTLIGHT; } return UNCOMPLETED; } return -1; }
2. ViewHolder点击事件中游标移动API误用
在ViewHolder的点击监听里,你使用了cursor.move(position);,这是对Cursor API的错误理解:move(int offset)是相对当前位置移动偏移量,而非直接跳转到指定索引位置,正确的写法应该是cursor.moveToPosition(position),同时建议增加判空避免异常:
itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = getAdapterPosition(); // 替换为正确的moveToPosition,并增加判空 if(cursor.moveToPosition(position)){ Note note = Utilities.cursorToNote(cursor); Intent intent = new Intent(itemView.getContext(), AddNoteActivity.class); intent.putExtras(note.sendNoteBundle()); intent.putExtra("type", true); itemView.getContext().startActivity(intent); } } });
额外优化建议
onBindViewHolder里的holder.imgIcon.performClick();会自动触发按钮点击,可能导致意外的状态变更(比如误标记任务完成),建议直接通过代码设置视图状态(比如修改图标、文本样式),而非模拟用户点击。- 当你调用
setCursor更新数据源后,记得调用notifyDataSetChanged()刷新列表,确保新数据能同步到UI。
修复以上问题后,你的RecyclerView应该就能正常显示全部20条数据了。
内容的提问来源于stack exchange,提问作者Zeroes
相关产品推荐
相关产品推荐

