gpt4 book ai didi

java - RecyclerView,notifyItemRemoved有时会删除无效项目,notifyDataSetChanged工作完美

转载 作者:行者123 更新时间:2023-12-01 18:02:17 50 4
gpt4 key购买 nike

我有一个带有 Adapter 和 ViewHolder 类的 RecyclerView,所以它有 3 个类,我在 ViewHolder 中添加了一个 onLongClick ,当长按时,所选项目将被删除,我将其删除如下:

            MyRV.Items.remove(getLayoutPosition());
MyRV.mAdapter.notifyItemRemoved(getLayoutPosition());

项目:

  1. 项目_1
  2. 项目_2
  3. 项目_3
  4. 项目_4
  5. Item_5

    Removing Item 2 - Item 2 removed .
    Removing Item 3 (which is item 2 now) - Item 1 removed (item - 1) .

我的数据项大约有 7 个,所以这就是发生的情况。第一次删除时,它会删除正确的项目,当您再次单击删除时,它会删除上述项目而不是删除所选项目,并且当大小为1时,它会因为大小无效而FC。

我的问题与此类似:using notifyItemRemoved or notifyDataSetChanged with RecyclerView in Android

但是从 itemRange 到 index + 1 ,答案都不起作用,没有一个。

public class MyAdapterextends RecyclerView.Adapter<MyViewHolder> {

private List<MyItem> itemList;
public Context context;

public MyAdapter(Context context, List<MyItem> itemList) {
this.itemList = itemList;
this.context = context;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.myitem, null);
return new MyViewHolder(layoutView);
}



@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {

holder.From.setText(itemList.get(holder.getAdapterPosition()).getFrom());
holder.To.setText(itemList.get(holder.getAdapterPosition()).getTo());


}

@Override
public int getItemCount() {
return this.itemList.size();
}
}

Activity

    LinearLayoutManager LinLayout = new LinearLayoutManager(MyActivity.this, LinearLayoutManager.VERTICAL, false);
mAdapter = new MyAdapter(MyActivity.this, Items);

RcView.setItemAnimator(new ItemAnimator());
RcView.setHasFixedSize(true);
RcView.setLayoutManager(LinLayout);
RcView.setAdapter(mAdapter);

最佳答案

尝试一下:

  adapter.remove(item);
adapter.notifyItemRemoved(position);
adapter.notifyItemRangeChanged(position, list.count());

关于java - RecyclerView,notifyItemRemoved有时会删除无效项目,notifyDataSetChanged工作完美,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957194/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com