RecyclerView 刷新闪烁

2019-05-21 12:37:34

参考地址 https://www.jianshu.com/p/4a2b18135447   这个没试过,不知道有没有用

前言

最近做项目,使用 RecycleView + SwipeRefreshLayout 刷新时,列表总是闪烁。

1、为什么会闪烁?
闪烁是 notifyDataSetChange 造成的。由于适配器不知道整个数据集中的哪些内容已经存在,在重新匹配 ViewHolder 时发生的。

当然,遇到这个问题时有去搜索一些答案,看到的很多都是去禁止 RecycleView 的默认动画,可惜这对我没什么用。下面的方法是对我有用的。

2、设置 setHasStableIds

下面给大家介绍一个方法 setHasStableIds

        /**
         * Indicates whether each item in the data set can be represented with a unique identifier
         * of type {@link java.lang.Long}.
         *
         * @param hasStableIds Whether items in data set have unique identifiers or not.
         * @see #hasStableIds()
         * @see #getItemId(int)
         */
        public void setHasStableIds(boolean hasStableIds) {            if (hasObservers()) {                throw new IllegalStateException("Cannot change whether this adapter has "
                        + "stable IDs while the adapter has registered observers.");
            }
            mHasStableIds = hasStableIds;
        }

long 类型的标识可以表示数据集中的每个项目。

DemoAdapter  mAdapter=new DemoAdapter();
mAdapter.setHasStablesId(true);

设置了这个属性后,我们必须给每个 Item 设置唯一的 ID。

3、重写 getItemId

在 Adapter 类中重写该方法来给每个 Item 一个唯一的ID。

@Overridepublic long getItemId(int position){    return items.get(position).getId();
}

这样写完之后闪烁就不再发生了。

getId() 只是我的一个方法,如果您没有一个类似 id 的唯一值,则可以使用字符串上的 hashCode() 来获取唯一值。结果也是一样的。



  • 2019-05-21 12:43:26

    (重要)RecycleView的缓存机制

    RecycleView的四级缓存是由三个类共同作用完成的,Recycler、RecycledViewPool和ViewCacheExtension。Recycler用于管理已经废弃或者与RecyclerView分离的ViewHolder,这里面有两个重要的成员,为可以看见的屏幕的内部缓存成员mAttachedScrap、mChangedScrap和滑出屏幕外的外部缓存成员mCachedViews二者共同完成ViewHolder的缓存;RecycledViewPool类是用来缓存整体所有的ViewHolder,是对mCachedViews缓存的补充;ViewCacheExtension是扩展内的缓存对象,默认不加载,需实现方法getViewForPositionAndType(Recycler recycler, int position, int type)来实现自己的缓存。接下来对四级缓存一步步介绍。

  • 2019-05-21 12:44:31

    对嵌套RecyclerView的优化

    RecyclerView 是一个更高级的 ListView ,它可以重用view避免额外创建太多的view从而带来流畅的滚动性能。RecyclerView通过叫做 View pool 的东西持有不再可见的 view ,让它可被回收

  • 2019-05-25 14:54:50

    commit your changes or stash them before you can merge

    Your local changes to the following files would be overwritten by merge:         protected/config/main.php Please, commit your changes or stash them before you can merge. --------------------- 作者:陈小峰_iefreer 来源:CSDN 原文:https://blog.csdn.net/iefreer/article/details/7679631 版权声明:本文为博主原创文章,转载请附上博文链接!

  • 2019-05-27 10:43:34

    IntelliJ IDEA中C盘文件过大怎么办

    当我在D:\ 安装完IDEA9.0之后,建立了一个工程,发现C:\Users\Administrator\.IntelliJIdea90 竟然增大到了500+M,并且随着使用在逐渐增大,这样占用系统盘资源是非常让人不爽的,那么如何将其修改到其他路径呢?

  • 2019-05-28 13:33:20

    BRVAH+MTRVA,复杂?不存在的

    言归正传,这样的一个首页,我们需要做怎么样的基础工作呢?或者说,碰到以后更复杂的页面我们应该怎么做?这里小提示下,不要再用什么类似ScrollView的这种东西了,诶,好像说的有点绝对,尽量不要用,这不是谷歌想要看到的,5.0谷歌推出了RecyclerView,从它的整个设计架构来看,简直就是为这而生的。而RecyclerView的视图是通过Adapter来渲染的。原始的Adapter,让人很蛋疼,重复工作太多,我们应该要有封装的思想,把最需要的部分提供出来,其它不用管。