在Android中将notifyItemRemoved或notifyDataSetChanged与RecyclerView一起使用 [英] using notifyItemRemoved or notifyDataSetChanged with RecyclerView in Android
问题描述
我正在创建一个卡片列表以使用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),可能是因为我保留了最高索引,即
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中将notifyItemRemoved或notifyDataSetChanged与RecyclerView一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!