[英]How can i maintain position in recycler adapter when removing an item?
I have a recycler adapter, in the view item there is a delete button (del). 我有一个回收站适配器,在查看项中有一个删除按钮(del)。 I use the following code in click event. 我在点击事件中使用以下代码。
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
holder.del.setTag(position);
holder.del.setOnClickLintener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
int pos= (int) v.getTag();
//remove view item
notifyItemRemoved(pos);
//remove equivalent arraylist item
listitems.remove(pos);
}
});
}
This does not update the tag values in the view items i assume because the onBindViewHolder()
is not called for the already existing items. 这不会更新我假设的视图项中的标记值,因为不会为已经存在的项调用onBindViewHolder()
。 How can i update the values or is there a different approach to this. 我如何更新值,或者有其他方法可以做到这一点。
You have to remove the item from the list and then you have to call notifyItemRemoved(pos)
. 您必须从列表中删除该项目,然后必须调用notifyItemRemoved(pos)
。
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
holder.del.setTag(position);
holder.del.setOnClickLintener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
int pos = (int) v.getTag();
//remove equivalent arraylist item
listitems.remove(pos);
//remove view item
notifyItemRemoved(pos);
new Handler().postDelayed( new Runnable(){
@override
void run(){
notifyDatasetChanged ()
}
},400);
}
});
}
Hope it helps:) 希望能帮助到你:)
Don't use the position as the tag if you want to use notifyItemRemoved and keep the removing animation. 如果要使用notifyItemRemoved并保留删除动画,请不要将该位置用作标签。 Use the Object in your items as the tag and find it when you need the index. 使用项目中的对象作为标签,并在需要索引时找到它。
@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
Object item = listitems.get(position);
holder.del.setTag(item);
holder.del.setOnClickLintener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Object item = (Object) v.getTag();
int pos = listitems.indexOf(item);
if (pos >= 0) {
//remove equivalent arraylist item
listitems.remove(pos);
//remove view item
notifyItemRemoved(pos);
}
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.