天天看点

RecyclerView 加载更多时遇到的闪烁问题RecyclerView 加载更多时遇到的闪烁问题

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就可以解决了,无需进行类似的设置。