【发布时间】:2017-12-06 16:20:22
【问题描述】:
我一直在努力寻找上述问题的答案,但似乎没有任何帖子有帮助。我有一个 RecyclerView 适配器,我从数据库中以列表形式获取数据:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
public List<Note> noteList;
private View.OnLongClickListener longClickListener;
private Context context;
public RecyclerViewAdapter(List<Note> noteList, View.OnLongClickListener longClickListener, Context context) {
this.noteList = noteList;
this.longClickListener = longClickListener;
this.context = context;
}
还有一个 ViewHolder,我有一个 onClickListener 来查找使用 getLayoutPosition() 单击的视图的位置:
static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView noteTitleText;
private TextView noteDescriptionText;
private TextView dateText;
private TextView weekText;
RecyclerViewHolder(View view) {
super(view);
noteTitleText = (TextView) view.findViewById(R.id.noteTitleText);
noteDescriptionText = (TextView) view.findViewById(R.id.noteDescriptionText);
dateText = (TextView) view.findViewById(R.id.dateText);
weekText = (TextView) view.findViewById(R.id.weekText);
view.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int position = getLayoutPosition();
// I want the noteList from the RecyclerViewAdapter here.
Note note = noteList.get(position);
Log.d("Item Clicked", String.valueOf(position));
}
}
目的是我需要 noteList 以及 onClick() 方法中来自 RecyclerViewAdapter 的所有注释,以使用意图填充 Activity。我该怎么办?
【问题讨论】:
-
如果您使用位置来索引支持适配器的数据结构(看起来像您),您应该使用
getAdapterPosition()而不是getLayoutPosition()。布局位置和适配器位置通常会同步,但如果适配器中的项目已被移动/更改并且 recyclerview 还没有机会绘制更新,则布局位置可能会报告不同的值。 -
@BenP。感谢您注意到这一点。
标签: java android android-recyclerview