gpt4 book ai didi

android - 在 Android 中将 notifyItemRemoved 或 notifyDataSetChanged 与 RecyclerView 一起使用

转载 作者:IT老高 更新时间:2023-10-28 13:17:08 31 4
gpt4 key购买 nike

我正在创建一个卡片列表以使用 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);
}

最佳答案

在 notifyItemRemoved(position);
之后使用 notifyItemRangeChanged(position, getItemCount());您不需要使用索引,只需使用位置即可。请参阅下面的代码。

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();
}

关于android - 在 Android 中将 notifyItemRemoved 或 notifyDataSetChanged 与 RecyclerView 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28189371/

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