简体   繁体   English

RecyclerView单击删除项目

[英]RecyclerView delete item on clicking it

I am trying to remove an item when clicking however it removes once and then i get the an error: 我试图在单击时删除项目,但是它删除一次,然后出现错误:

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

} }

I understand that it doesn't update the positions after deleting the first item, it should update them right? 我知道删除第一项后它不会更新职位,应该更新吗? but it doesn't, how can i fix it? 但是没有,我该如何解决? I would appreciate any help, Thank you! 我将不胜感激,谢谢!

Use notifyItemRemoved 使用notifyItemRemoved

notifyItemRemoved(index)

Notify any registered observers that the item previously located at position has been removed from the data set. 通知任何注册的观察者先前位于该位置的项目已从数据集中删除。 The items previously located at and after position may now be found at oldPosition - 1. 现在可以在oldPosition-1上找到以前位于位置和位置之后的项目。

and then 接着

notifyItemRangeChanged(index, cards.size());

Check this stackoverflow answer 检查此stackoverflow答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM