在 Android 中使用带 RecyclerView 的 notifyItemRemoved 或 notifyDataSetChanged [英] using notifyItemRemoved or notifyDataSetChanged with RecyclerView in Android

查看:18
本文介绍了在 Android 中使用带 RecyclerView 的 notifyItemRemoved 或 notifyDataSetChanged的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建要使用 RecyclerView 显示的卡片列表,其中每张卡片都有一个按钮,用于从列表中删除该卡片.

I am creating a list of cards to display using the RecyclerView, where each card has a button to remove that card from the list.

当我使用 notifyItemRemoved() 删除 RecyclerView 中的卡片时,它会删除该项目并动画良好,但列表中的数据未正确更新.

When i use notifyItemRemoved() to remove the card in the RecyclerView, it removes the item and animates fine but the data in the list is not updated correctly.

如果不是那样,我切换到 notifyDataSetChanged() 那么列表中的项目会被删除并正确更新,但卡片不会动画.

If instead of that, i switch to the notifyDataSetChanged() then the items in list are removed and updated correctly, but then the cards dont animate.

有人在使用 notifyItemRemoved() 方面有任何经验并且知道为什么它的行为与 notifyDataSetChanged 不同吗?

Does someone has any experience in using the notifyItemRemoved() and know why it behaves differently than notifyDataSetChanged?

这是我正在使用的一些代码:

Here is some peiece of code that i am using:

private List<DetectedIssue> issues = new ArrayList<DetectedIssue>();

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    if(position >0){
        RiskViewHolder riskHolder = (RiskViewHolder)holder;
        final int index = position - 1;
        final DetectedIssue anIssue = issues.get(index);

        riskHolder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    int index = issues.indexOf(anIssue);
                    issues.remove(anIssue);
                    notifyItemRemoved(index);

                    //notifyDataSetChanged();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

@Override
public int getItemCount() {
    return (issues.size()+1);
}

推荐答案

正如@pskink 所建议的那样,在我的情况下,notifyItemRemoved(index+1) 应该是 (index+1),可能因为我为标题保留顶部索引,即 position=0.

As @pskink suggested it was supposed to be (index+1) in my case with notifyItemRemoved(index+1), probably because i am reserving the top index i.e. position=0 for a header.

这篇关于在 Android 中使用带 RecyclerView 的 notifyItemRemoved 或 notifyDataSetChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆