我的回收站视图适配器如下
@Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).
inflate(R.layout.contacts_list_item, viewGroup, false);
return new ContactViewHolder(itemView);
}
@Override
public void onBindViewHolder(ContactViewHolder viewHolder, int position) {
super.onBindViewHolder(viewHolder, position);
viewHolder.removeContact.setTag(position);
Contact contact = contacts.get(position);
viewHolder.contactName.setText(contact.getContactName());
viewHolder.contactNumber.setText(contact.getContactNumber());
viewHolder.removeContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer taggedPosition = (Integer) v.getTag();
Log.wtf("ad","Posirtion"+ Integer.toString(taggedPosition));
contacts.remove(Integer.parseInt(Integer.toString(taggedPosition)));
notifyItemRemoved(Integer.parseInt(Integer.toString(taggedPosition)));
}
});
}
@Override
public int getItemCount() {
return contacts.size();
}
public void removeItem(int pos) {
contacts.remove(pos);
// notifyItemRemoved(pos);
}
public void add(Contact contact, int position) {
contacts.add(position, contact);
notifyItemInserted(position);
}
我的观看者是
class ContactViewHolder extends RecyclerView.ViewHolder {
public TextView contactName,contactNumber;
public ImageButton removeContact;
public ContactViewHolder(View itemView) {
super(itemView);
contactName= (TextView) itemView.findViewById(R.id.tv_contactName);
contactNumber= (TextView) itemView.findViewById(R.id.tv_contactNumber);
removeContact= (ImageButton) itemView.findViewById(R.id.ib_removeItem);
}
}
问题是我似乎无法获得viewHolder.removeContact
的位置。我想要实现的是在点击viewHolder.removeContact
时删除行。我尝试通过getTag()获取位置方法,但它只给我一个位置,即0。
答案 0 :(得分:1)
感谢@ pskink.Thanks。解决了这个问题我所做的就是将我的适配器和contacts
arraylist的引用传递给我的视图持有者类
@Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).
inflate(R.layout.contacts_list_item, viewGroup, false);
return new ContactViewHolder(itemView,this,contacts);
}
其中itemView
是要返回的视图,this
是适配器引用,而contacts
是我必须在按钮点击时更新的arraylist。我的ViewHolder类像这样lookes
class ContactViewHolder extends RecyclerView.ViewHolder {
public TextView contactName,contactNumber;
public ImageButton removeContact;
private List<Contact> contacts1;
private ContactsAdapter contactsAdapter1;
public ContactViewHolder(View itemView, ContactsAdapter contactsAdapter, final List<Contact> contacts) {
super(itemView);
this.contacts1=contacts;
this.contactsAdapter1=contactsAdapter;
contactName= (TextView) itemView.findViewById(R.id.tv_contactName);
contactNumber= (TextView) itemView.findViewById(R.id.tv_contactNumber);
removeContact= (ImageButton) itemView.findViewById(R.id.ib_removeItem);
removeContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contacts1.remove(getPosition());
contactsAdapter1.notifyItemRemoved(getPosition());
}
});
}
}