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);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…