我试图在点击时移除一个项目,但是它会移除一次,然后我收到一个错误:
ERROR
Process: com.example.cardgame, PID: 3345
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 10(offset:10).state:11
CODE
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);
}
}
}
我知道删除第一项后它没有更新位置,它应该更新吗?但它没有,我该如何解决?我将不胜感激任何帮助,谢谢!
答案 0 :(得分:2)
notifyItemRemoved(index)
通知任何已注册的观察员,之前位于该位置的物品已从数据集中删除。之前位于位置和位置之后的项目现在可以在oldPosition - 1找到。
然后
notifyItemRangeChanged(index, cards.size());