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() - 1; i >= 0; 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就可以解决了,无需进行类似的设置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值