我在单击时试图删除项目,但它会删除一次,然后我得到一个错误:
错误
Process: com.example.cardgame, PID: 3345
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 10(offset:10).state:11
代码
public class HandViewAdapter extends RecyclerView.Adapter<HandViewAdapter.ViewHolder>{
private ArrayList<Card> cards;
private Context context;
public HandViewAdapter(ArrayList<Card> cards, Context context) {
this.cards = cards;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View cardView = inflater.inflate(R.layout.card, parent, false);
return new ViewHolder(cardView);
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
Card card = this.cards.get(position);
if (position == 0) {
card.setStatus(CardStatus.down);
} else {
card.setStatus(CardStatus.up);
}
// Here i put the listener since i have tried other methods but i have no success to run them
holder.cardLayoutView.getCardView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
remove(position);
}
});
}
@Override
public int getItemCount() {
return this.cards.size();
}
public Card remove(int index) {
cards.remove(index);
notifyItemChanged(index);
notifyItemRangeChanged(index, cards.size());
return null;
}
public static class ViewHolder extends RecyclerView.ViewHolder implements CardBehavior {
public CardLayoutView cardLayoutView;
public ViewHolder(View view) {
super(view);
this.cardLayoutView = new CardLayoutView(view);
}
@Override
public void faceDown() {
this.cardLayoutView.faceDown();
}
@Override
public void faceUp(Card card, Context context) {
this.cardLayoutView.faceUp(card, context);
}
}
}
我知道它在删除第一个项目后不会更新位置,应该对其进行更新吗?但这不是,我该如何解决?感谢任何帮助,谢谢!
使用notifyitemrever
notifyItemRemoved(index)
通知任何注册的观察者,先前位于位置的项目已从数据集中删除。现在可以在OldPosition -1。
上找到以前位于位置和之后的项目。
,然后
notifyItemRangeChanged(index, cards.size());
检查此stackoverflow答案