在RecyclerView上获取对ViewHolder的引用单击

这是我第一次尝试实施RecyclerView 。 我在AdapterViewHolder类之间实现了一个Callback接口来处理UI元素(按钮)上的Click Events。 我在ViewHolder单击发生时对ViewHolder的引用时遇到问题。我可以单击列表中第一个项目的Button ,但是我定义的操作是在我的viewholder视图中的最后一个查看器上执行的。 我终于想通过我的界面传递位置,但我很难理解如何从中获取对该视图的引用。

  public class RoomAdapter extends RecyclerView.Adapter { List mRooms; public RoomAdapter(List rooms) { mRooms = rooms; } @Override public RoomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { final View viewItem = LayoutInflater .from(viewGroup.getContext()) .inflate(R.layout.room_rv_item,viewGroup,false); return vh = new RoomViewHolder(viewItem,new IRoomViewClick() { @Override public void editname(int pos) { } }); } @Override public void onBindViewHolder(RoomViewHolder roomViewHolder, int i) { Room r = getItem(i); roomViewHolder.label.setText(r.name); } public Room getItem(int position) { return mRooms.get(position); } @Override public long getItemId(int position) { return mRooms.get(position).getId(); } @Override public int getItemCount() { return mRooms.size(); } public static class RoomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView label; Button editBtn; LinearLayout labelView; Button saveBtn; Button deleteBtn; EditText editNameET; IRoomViewClick mListener; public RoomViewHolder(View itemView, IRoomViewClick listener) { super(itemView); labelView = (LinearLayout) itemView.findViewById(R.id.labelview); mListener = listener; editBtn =(Button) itemView.findViewById(R.id.editbtn); editBtn.setOnClickListener(this); label = (TextView) itemView.findViewById(R.id.room_listitem_label); } @Override public void onClick(View view) { int pos = getPosition(); mListener.editname(pos); } } public static interface IRoomViewClick { public void editname(int pos); } } 

在此处输入图像描述

你可以在editBtn中为editBtn设置一个标签:

  public RoomViewHolder(View itemView, IRoomViewClick listener) { .... editBtn =(Button) itemView.findViewById(R.id.editbtn); //add tag for this view editBtn.setTag(this); .... } 

并在onClick获取它

  @Override public void onClick(View view) { //getTag RoomViewHolder holder = (RoomViewHolder )(view.getTag()); int pos = getPosition(); mListener.editname(pos); ... } 

实际上,你可以通过在RecyclerView上调用getChildViewHolder(View child)来做得比getTag更好:

 @Override public void onClick(View v) { MyHolder holder = (MyHolder) mRecyclerView.getChildViewHolder(v); holder.textView.setText("Clicked!"); } 
 @Override public void onClick(View v) { int pos = getAdapterPosition(); //getPosition() is deprecated notifyItemChanged(pos); } 

notifyItemChanged将通知你的onBindViewHolder,然后你可以做这样的事情

 public void onBindViewHolder(RoomViewHolder roomViewHolder, int i) { Room r = getItem(i); roomViewHolder.label.setText(r.name); if(i == pos){ // Do Something } } 

每当您单击该项时,它将更改pos’值并触发// Do Something

RecycleViewcertificate, RecycleView在视图布局参数中保存视图位置,因此如果您只是希望视图位置从列表中获取正确的项目,您可以使用:

 RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) v.getLayoutParams(); lp.getViewPosition();