RecyclerView 加載更多時遇到的閃爍問題
當用RecyclerView進行加載更多資料的時候,不要使用notifyDataSetChanged()。該方法誰重新整理整體的資料集合,所有的view重新重新整理,出現了閃爍的問題,從源碼進行分析
public abstract static class Adapter<VH extends ViewHolder> {
...
public final void notifyDataSetChanged() {
mObservable.notifyChanged();
}
}
static class AdapterDataObservable extends Observable<AdapterDataObserver> {
public void notifyChanged() {
// since onChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - ; i >= ; i--) {
mObservers.get(i).onChanged();
}
}
}
從代碼可以看出來,該方法是對所有的資料進行了重新整理,如果繼續追蹤下去,其實就是更新資料,之後recyclerView調用了requestLayout()方法
RecyclerView其實提供了更好的方法來針對發生了變化的資料
* @see #notifyItemChanged(int)
* @see #notifyItemInserted(int)
* @see #notifyItemRemoved(int)
* @see #notifyItemRangeChanged(int, int)
* @see #notifyItemRangeInserted(int, int)
* @see #notifyItemRangeRemoved(int, int)
從名稱就能看出具體的作用了,我們看看常用的方法
/**
* Notify any registered observers that the <code>itemCount</code> items starting at
* position <code>positionStart</code> have changed.
* Equivalent to calling <code>notifyItemRangeChanged(position, itemCount, null);</code>.
*
* <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);
}
不需要多說看看注釋和方法名稱就能體會到他的作用了,他隻會更新從positionStart開始的itemCount的個資料變化,而之前的view和資料是不會發生變化的。
使用該方法就可以解決閃爍問題了
網上有說使用
(recyclerCategory.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
來解決閃爍問題的,該方法取消了adapter自帶的動畫效果,但是我測試隻需使用notifyItemRangeChanged就可以解決了,無需進行類似的設定。