RecyclerView 區域性重新整理的坑

Mr_凌宇發表於2019-03-04

前言

相信童鞋們都用過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。講道理我們到了這一步就已經可以滿足需求了,然而…事實不講道理:

一閃一閃亮晶晶
一閃一閃亮晶晶

額…原諒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,執行,跑下效果為:

不會閃屏.gif
不會閃屏.gif

確實是解決了。

相關文章