[英]How to pass List<E> from RecyclerView Adapter to RecyclerView Holder?
I've been trying to find the answer to my question above but no post seems to help. 我一直在尝试找到上述问题的答案,但似乎没有任何帮助。 I have a RecyclerView Adapter where I get the data as List from a database:
我有一个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;
}
And a ViewHolder where I have an onClickListener to find the position of the view clicked using getLayoutPosition()
: 还有一个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));
}
}
The purpose is that I need the noteList with all the notes from the RecyclerViewAdapter in the onClick() method to populate an Activity using an intent. 目的是我需要noteList以及onClick()方法中来自RecyclerViewAdapter的所有注释,以使用意图填充Activity。 How should I go about this?
我应该怎么做?
After trying out solutions for an hour, here's what I settled on. 在尝试了一个小时的解决方案之后,这就是我的解决方案。 Instead of implementing OnClickListener in ViewHolder, I implemented it in RecyclerViewAdapter in onBindViewHolder() method, as:
我没有在ViewHolder中实现OnClickListener,而是在RecyclerViewAdapter中的onBindViewHolder()方法中实现了它,如下所示:
@Override
public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {
final Note note = noteList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// The note and noteList can be accessed here.
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.