首页 > 解决方案 > android Recyclerview删除项目不会更新适配器的获取项目计数

问题描述

我有一个带有滑动功能的 RecyclerView 以显示删除和编辑按钮。

我补充说:adapter.notifyItemRemoved(position)这个: adapter.notifyItemRangeChanged(0, adapter.getItemCount());

单击显示的删除按钮时,删除该项目的动画将起作用,并且该项目已从我的数据库中删除

但是然后删除的项目重新出现在我的回收站视图中。当我更改活动并返回到带有 recyclerview 的活动时,我应该看到的列表很好。

如果我删除“notifyItemRangeChanged”代码,列表会更新并重复最后一项。

我认为这是我的适配器的 getItemCount 没有正确更新。所以我尝试不同的是首先调用生成列表的方法。这成功了,但是我的删除项目动画现在消失了,因为我猜它只是跳过重新生成列表....

有任何想法吗?

提前感谢您的反馈!

****************** 更新 - 添加适配器类代码 **************** 公共类 RVCategoryAdapter 扩展 RecyclerView.Adapter { Context context ; 列出类别ItemList;

    public RVCategoryAdapter(Context context, List<CategoryItem> categoryItemList) {
        this.context = context;
        this.categoryItemList = categoryItemList;
    }

    @NonNull
    @Override
    public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.category_item_layout, parent, false);

        return new CategoryViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull CategoryViewHolder holder, final int position) {
        final int categoryID;
        final String categoryTitle;

        Glide.with(context).load(categoryItemList.get(position).getImage()).into(holder.ivCategoryIcon);
        holder.txtCatID.setText(""+categoryItemList.get(position).getCategoryID());
        holder.txtCategoryTitle.setText(categoryItemList.get(position).getTitle());
        holder.txtCategoryDesc.setText(categoryItemList.get(position).getDescription());

        categoryID = Integer.parseInt(holder.txtCatID.getText().toString());
        categoryTitle = holder.txtCategoryTitle.getText().toString();
        holder.cardViewItemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, NotesListActivity.class);
                intent.putExtra("CategoryID", categoryID);
                intent.putExtra("CategoryTitle", categoryTitle);
                context.startActivity(intent);
            }
        });
    }

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

标签: androidandroid-recyclerview

解决方案


在您的滑动删除按钮中,单击侦听器也将您的项目从列表中删除。我建议您在适配器中添加删除功能。然后在该方法中从列表中删除您的项目并调用 notifyItemRemoved。

public void delete(int position){
    categoryItemList.remove(position);
    notifyItemRemoved(position);
}

推荐阅读