RecycleView 刪除Item 遇到的問題

場景:RecycleView 刪除Item

問題:
holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    contentList.remove(position);
                    notifyItemRemoved(position);            
                }
            });

使用上方代碼會出現數組越界出現的崩潰/ 刪除後排序混亂

解決方法:

holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int layoutPosition = viewHolder.getLayoutPosition();
                            //getLayoutPositon(數值包括 getHeadCount()) 且從1開始計數  對應mCommunicationList-1
                            mCommunicationList.remove(layoutPosition - 1 - headViewCount());
                            notifyItemRemoved(layoutPosition);           
                }
            });

注意:notifyItemRemoved的position值: 包含recycleView 的headView個數 以及 從1開始計數

可以選擇在 notifyItemRemoved() 使用notifyItemRangeChanged()。

remove:把數據從list中remove掉,
notifyItemRemoved:顯示動畫效果
notifyItemRangeChanged:對於被刪掉的位置及其後range大小範圍內的view進行重新onBindViewHolder

notifyItemRangeChanged 源碼解釋 :

   /**
         * Notify any registered observers that the <code>itemCount</code> items starting at
         * position <code>positionStart</code> have changed.
         *
         * <p>This is an item change event, not a structural change event. It indicates that
         * any reflection of the data in the given position range is out of date and should
         * be updated. The items in the given range retain the same identity.</p>
         *
         * @param positionStart Position of the first item that has changed
         * @param itemCount Number of items that have changed
         *
         * @see #notifyItemChanged(int)
         */
        public final void notifyItemRangeChanged(int positionStart, int itemCount) {
            mObservable.notifyItemRangeChanged(positionStart, itemCount);
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章