美文网首页
RecyclerView 局部刷新的坑

RecyclerView 局部刷新的坑

作者: 々志尚 | 来源:发表于2019-10-16 18:17 被阅读0次

    前言

    相信童鞋们都用过RecyclerView,假设说要我们做一个列表更新Item的功能,相信大部分同学都会这么写的:

    
      /**
         * 更新列表数据某一项的packageName
         *
         * @param position    下标
         * @param packageName 要替换的文本名
         */
        public void updateItem(int position, String packageName) {
            if (position >= 0 && position < data.size()) {
                data.get(position).setPackageName(packageName);
            }
            notifyDataSetChanged();
        }
    
    

    踩坑

    而我们要做的是一个下载列表,在下载的callback里面我们要去更新列表的progressBar还有Button的文本:

    Activity中获取到下载的callback:

     @Override
            public void onProgress(long finished, long total, int progress) {
                XLog.e(mInfoBean.getDownLoadUrl() + "-----------||||||" + progress);
                String downloadPerSize = Kits.File.getDownloadPerSize(finished, total);
                mInfoBean.setDownLoadStatus(STATUS_DOWNLOADING);
                mInfoBean.setDownloadPerSize(downloadPerSize);
                mInfoBean.setProgress(progress);
                if (isCurrentListViewItemVisible(mPosition)) {
                    mTestDownLoadAdapter.setProgress(progress, mPosition, downloadPerSize);
                }
            }
    
    

    适配器中暴露的用于更新progressBar进度的方法

      /**
         * 暴露用于修改进度值的方法
         *
         * @param progress
         * @param position
         * @param progressStr
         */
        public void setProgress(int progress, int position, String progressStr) {
            data.get(position).setProgress(progress);
            data.get(position).setDownloadPerSize(progressStr);
            notifyItemChanged(position);
        }
    
    

    适配器的onBindViewHolder()中处理数据结果

     @Override
        public void onBindViewHolder(final TestDownLoadHolder holder, final int position) {
            final AppInfoBean appInfoBean = data.get(position);
            if (appInfoBean != null) {
                ILFactory.getLoader().loadNet(holder.mIvDownPic, appInfoBean.getDownLoadPic(), ImgOptions.getDefImaOptions());
                holder.mPbDownProgress.setProgress(appInfoBean.getProgress());
                holder.mBtDownLoad.setText(appInfoBean.getDownloadPerSize());
                holder.mBtDownLoad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (getRecItemClick() != null) {
                            getRecItemClick().onItemClick(position, appInfoBean, 0, holder);
                        }
                    }
                });
            }
    
        }
    
    

    这里我们使用的是notifyItemChanged局部刷新而不是notifyDataSetChanged。讲道理我们到了这一步就已经可以满足需求了,然而...事实不讲道理:

    image

    额...原谅demo画得太丑了。这里我们可以发现....为毛我的图片...一闪一闪的,亮瞎我的狗眼了。
    至于为什么会闪动?
    猜测:

    1. ImageView的宽高问题,重新计算导致了闪动
    2. 更新到了ImageView,然后glide又重新加载了一次图片。
    3. 刷新到了ImageView,这个item渲染了一次。

    解疑:

    • 采用了写死宽高的方法,但是!页面还是会闪动...gif就不传了,录制好麻烦。猜测1已经否决了。
    • 注释掉
     ILFactory.getLoader().loadNet(holder.mIvDownPic, appInfoBean.getDownLoadPic(), ImgOptions.getDefImaOptions());
    
    

    在xml中写入

      android:src="@mipmap/ic_launcher"
    
    

    测试下,结果还是会闪动...那猜测2又不对了!

    • 重新理下,我们需要更新的是Button和progressBar,其实ImageView我们是不需要额外去更新的。

    那我们的问题就聚焦在如何只更新一部分控件,其他控件不动

    解决

    至于怎么解决呢...扒源码:

       /**
             * Notify any registered observers that the item at <code>position</code> has changed.
             * Equivalent to calling <code>notifyItemChanged(position, null);</code>.
             *
             * <p>This is an item change event, not a structural change event. It indicates that any
             * reflection of the data at <code>position</code> is out of date and should be updated.
             * The item at <code>position</code> retains the same identity.</p>
             *
             * @param position Position of the item that has changed
             *
             * @see #notifyItemRangeChanged(int, int)
             */
            public final void notifyItemChanged(int position) {
                mObservable.notifyItemRangeChanged(position, 1);
            }
    
    
     /**
             * Notify any registered observers that the item at <code>position</code> has changed with an
             * optional payload object.
             *
             * <p>This is an item change event, not a structural change event. It indicates that any
             * reflection of the data at <code>position</code> is out of date and should be updated.
             * The item at <code>position</code> retains the same identity.
             * </p>
             *
             * <p>
             * Client can optionally pass a payload for partial change. These payloads will be merged
             * and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the
             * item is already represented by a ViewHolder and it will be rebound to the same
             * ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing
             * payloads on that item and prevent future payload until
             * {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume
             * that the payload will always be passed to onBindViewHolder(), e.g. when the view is not
             * attached, the payload will be simply dropped.
             *
             * @param position Position of the item that has changed
             * @param payload Optional parameter, use null to identify a "full" update
             *
             * @see #notifyItemRangeChanged(int, int)
             */
            public final void notifyItemChanged(int position, Object payload) {
                mObservable.notifyItemRangeChanged(position, 1, payload);
            }
    
    

    在这里我们看到一句话:

       @param payload Optional parameter, use null to identify a "full" update
    
    

    传入“null”就是更新全部!那我们调用的时候是传入什么呢!看下:

      public final void notifyItemChanged(int position) {
                mObservable.notifyItemRangeChanged(position, 1);
            }
    
    

    继而调用:

     public void notifyItemRangeChanged(int positionStart, int itemCount) {
                notifyItemRangeChanged(positionStart, itemCount, null);
            }
    
    

    继而调用:

      public void notifyItemRangeChanged(int positionStart, int itemCount, Object payload) {
                // since onItemRangeChanged() 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).onItemRangeChanged(positionStart, itemCount, payload);
                }
            }
    
    

    [捂脸] 一个大写的null...

    OK,那我们修改下我们的调用方法:

     /**
         * 暴露用于修改进度值的方法
         *
         * @param progress
         * @param position
         * @param progressStr
         */
        public void setProgress(int progress, int position, String progressStr) {
            data.get(position).setProgress(progress);
            data.get(position).setDownloadPerSize(progressStr);
            notifyItemChanged(position, 1);
        }
    
        /**
         * 暴露用于修改按钮文字值的方法
         *
         * @param position
         * @param buttonStr
         */
        public void setButtonStatus(int position, String buttonStr) {
            data.get(position).setDownloadPerSize(buttonStr);
            notifyItemChanged(position, 1);
        }
    
    

    这里我们传入了一个 “1”,这个1是随意传入的,其他值也可以。

    继而我们需要重写onBindViewHolder方法如下:

     @Override
        public void onBindViewHolder(TestDownLoadHolder holder, int position, List<Object> payloads) {
            XLog.e("--------------------------has  payloads");
            if (payloads.isEmpty()) {
                XLog.e("--------------------------no  payloads");
                onBindViewHolder(holder, position);
            } else {
                XLog.e("--------------------------false  payloads");
                final AppInfoBean appInfoBean = data.get(position);
                if (appInfoBean != null) {
                    holder.mPbDownProgress.setProgress(appInfoBean.getProgress());
                    holder.mBtDownLoad.setText(appInfoBean.getDownloadPerSize());
                }
            }
        }
    
        @Override
        public void onBindViewHolder(final TestDownLoadHolder holder, final int position) {
            final AppInfoBean appInfoBean = data.get(position);
            if (appInfoBean != null) {
                ILFactory.getLoader().loadNet(holder.mIvDownPic, appInfoBean.getDownLoadPic(), ImgOptions.getDefImaOptions());
                holder.mPbDownProgress.setProgress(appInfoBean.getProgress());
                holder.mBtDownLoad.setText(appInfoBean.getDownloadPerSize());
                holder.mBtDownLoad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (getRecItemClick() != null) {
                            getRecItemClick().onItemClick(position, appInfoBean, 0, holder);
                        }
                    }
                });
            }
    
        }
    
    

    可以看到我们这里有2个onBindViewHolder方法,在第一个OnBindViewHolder里面我们需要判断下payloads是否为空,如果为空的话执行默认的OnBindViewHolder方法,如果不为空的话,执行我们自己的局部刷新方法

     if (payloads.isEmpty()) {
                XLog.e("--------------------------no  payloads");
                onBindViewHolder(holder, position);
            } else {
                XLog.e("--------------------------false  payloads");
                final AppInfoBean appInfoBean = data.get(position);
                if (appInfoBean != null) {
                    holder.mPbDownProgress.setProgress(appInfoBean.getProgress());
                    holder.mBtDownLoad.setText(appInfoBean.getDownloadPerSize());
                }
            }
    
    

    贴下完整的适配器方法:

    /**
     * @author Ly
     * @date 2017/10/26
     */
    
    public class TestDownLoadAdapter extends SimpleRecAdapter<AppInfoBean, TestDownLoadAdapter.TestDownLoadHolder> {
        public TestDownLoadAdapter(Context context) {
            super(context);
        }
    
        @Override
        public TestDownLoadHolder newViewHolder(View itemView) {
            return new TestDownLoadHolder(itemView);
        }
    
        /**
         * 更新列表数据某一项的packageName
         *
         * @param position    下标
         * @param packageName 要替换的文本名
         */
        public void updateItem(int position, String packageName) {
            if (position <= 0 && position < data.size()) {
                data.get(position).setPackageName(packageName);
            }
            notifyDataSetChanged();
        }
    
        /**
         * 暴露用于修改进度值的方法
         *
         * @param progress
         * @param position
         * @param progressStr
         */
        public void setProgress(int progress, int position, String progressStr) {
            data.get(position).setProgress(progress);
            data.get(position).setDownloadPerSize(progressStr);
            notifyItemChanged(position, 1);
        }
    
        /**
         * 暴露用于修改按钮文字值的方法
         *
         * @param position
         * @param buttonStr
         */
        public void setButtonStatus(int position, String buttonStr) {
            data.get(position).setDownloadPerSize(buttonStr);
            notifyItemChanged(position, 1);
        }
    
        @Override
        public int getLayoutId() {
            return R.layout.item_test_down;
        }
    
        @Override
        public void onBindViewHolder(TestDownLoadHolder holder, int position, List<Object> payloads) {
            XLog.e("--------------------------has  payloads");
            if (payloads.isEmpty()) {
                XLog.e("--------------------------no  payloads");
                onBindViewHolder(holder, position);
            } else {
                XLog.e("--------------------------false  payloads");
                final AppInfoBean appInfoBean = data.get(position);
                if (appInfoBean != null) {
                    holder.mPbDownProgress.setProgress(appInfoBean.getProgress());
                    holder.mBtDownLoad.setText(appInfoBean.getDownloadPerSize());
                }
            }
        }
    
        @Override
        public void onBindViewHolder(final TestDownLoadHolder holder, final int position) {
            final AppInfoBean appInfoBean = data.get(position);
            if (appInfoBean != null) {
                ILFactory.getLoader().loadNet(holder.mIvDownPic, appInfoBean.getDownLoadPic(), ImgOptions.getDefImaOptions());
                holder.mPbDownProgress.setProgress(appInfoBean.getProgress());
                holder.mBtDownLoad.setText(appInfoBean.getDownloadPerSize());
                holder.mBtDownLoad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (getRecItemClick() != null) {
                            getRecItemClick().onItemClick(position, appInfoBean, 0, holder);
                        }
                    }
                });
            }
    
        }
    
        /**
         * 开启下载
         *
         * @param position
         */
        public void doStartDownLoad(int position) {
    
        }
    
        /**
         * 开启安装
         *
         * @param position
         */
        public void doInstall(int position) {
    
        }
    
        /**
         * 开启停止下载
         *
         * @param position
         */
        public void doPauseDownLoad(int position) {
    
        }
    
        public static class TestDownLoadHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.iv_down_pic)
            public ImageView mIvDownPic;
            @BindView(R.id.pb_down_progress)
            public ProgressBar mPbDownProgress;
            @BindView(R.id.bt_down_load)
            public Button mBtDownLoad;
    
            TestDownLoadHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
        }
    }
    
    

    Ok,运行,跑下效果为:

    image

    确实是解决了。

    相关文章

      网友评论

          本文标题:RecyclerView 局部刷新的坑

          本文链接:https://www.haomeiwen.com/subject/hsliyctx.html