2016-12-20 87 views
0

我想,当点击删除项目但是它删除一次,然后我得到了一个错误:RecyclerView上单击删除项目它

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

}

据我所知,它删除第一个项目后不更新位置,它应该更新他们对吗?但它不,我如何解决它?我将不胜感激任何帮助,谢谢!

回答

2

使用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.

然后

notifyItemRangeChanged(index, cards.size()); 

检查this stackoverflow answer

+0

感谢它,这样的工作是什么样的区别呢? – kobbycoder

+0

@ kobbycoder更新了解答链接 –

+0

感谢兄弟,我感谢您的帮助。 – kobbycoder