这是我第一次尝试实施RecyclerView
。我在Callback
和Adapter
类之间实现了ViewHolder
接口,以处理UI元素(按钮)上的Click事件。我在获取点击发生的ViewHolder
时遇到问题。我可以点击列表中第一个项目的Button
,但是我定义的操作是在最后一个上执行的我的回收站视图中的viewholder
。我终于想通过我的界面传递这个位置,但是我很难理解如何从中获取对该视图的引用。
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);
}
}
答案 0 :(得分:22)
您可以在editBtn
中为onBindViewHolder
设置标记:
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);
...
}
答案 1 :(得分:13)
实际上,通过在RecyclerView上调用getTag
,您可以做得比getChildViewHolder(View child)
更好:
@Override
public void onClick(View v) {
MyHolder holder = (MyHolder) mRecyclerView.getChildViewHolder(v);
holder.textView.setText("Clicked!");
}
答案 2 :(得分:6)
@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&#39;值并触发// Do Something
答案 3 :(得分:2)
证明RecycleView
将视图位置保存在视图布局参数中,因此如果您只想让视图位置从列表中获取正确的项目,则可以使用此项:
RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) v.getLayoutParams();
lp.getViewPosition();