Eric Cumbee Eric Cumbee - 5 months ago 96
Android Question

Getting a Reference to ViewHolder on RecyclerView Click

This is my first attempt at implementing the RecyclerView. I have implemented a Callback interface between the Adapter and the ViewHolder Class to handle Click Events on the UI elements(buttons). I am having problems getting a reference to the ViewHolder that the click occurred in. I can click the Button for the first item in the list, however the action that i'd defined is performed on the last viewholder in my recycler view. I finally figured out to pass the position through my interface, but I'm struggling to understand how to get a reference to that viewholder from it.

public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.RoomViewHolder>
{
List<Room> mRooms;
public RoomAdapter(List<Room> 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);
}

}


enter image description here

Answer

you can set a tag for the editBtn in onBindViewHolder:

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

and get it in onClick

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