在Android中使用notifyItemRemoved或notifyDataSetChanged与RecyclerView

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

当我使用notifyItemRemoved()来删除RecyclerView中的卡,它会删除项目和动画很好,但列表中的数据不会正确更新。

如果不是这样,我切换到notifyDataSetChanged(),然后列表中的项目被删除和更新正确,但然后这些卡不动画。

有人有使用notifyItemRemoved()的任何经验,知道为什么它的行为不同于notifyDataSetChanged?

这里是我使用的一些代码段:

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);
}
使用notifyItemRangeChanged(position,getItemCount()); after notifyItemRemoved(position);
你不需要使用索引,只需使用位置。见下面的代码。

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;

        riskHolder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    issues.remove(position);
                    notifyItemRemoved(position);
                    //this line below gives you the animation and also updates the
                    //list items after the deleted item
                    notifyItemRangeChanged(position, getItemCount());

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

@Override
public int getItemCount() {
    return issues.size();
}
相关文章
相关标签/搜索