CountDownTimer在recyclerview里造成的混乱问题的解决

1.在ViewHolder里定义CountDownTimer

public static class ProductViewHolder extends BaseViewHolder {
        private CountDownTimer countDownTimer;
        public ProductViewHolder(View view) {
            super(view);
        }

        public ViewDataBinding getBinding() {
            return (ViewDataBinding) itemView.getTag(R.id.BaseQuickAdapter_databinding_support);
        }
    }

2.在Adapter里初始化SparseArray

private SparseArray timerArray;
    public ProductAdapter(int layoutResId, @Nullable List data) {
        super(layoutResId, data);
        timerArray = new SparseArray<>();
    }

3.在绑定数据的方法里加以下代码

if (helper.countDownTimer != null){
                helper.countDownTimer.cancel();
            }
            helper.countDownTimer = new CountDownTimer(orderEnd - currentTimeMillis, 1000L) {
                @Override
                public void onTick(long millisUntilFinished) {
                    ((TextView) helper.getView(R.id.text_time)).setText(stakingProduct.getProductEndTime(mContext,millisUntilFinished));
                }

                @Override
                public void onFinish() {
                    ((TextView) helper.getView(R.id.text_time)).setVisibility(View.GONE);
                    ((TextView) helper.getView(R.id.text_time_string)).setVisibility(View.GONE);
                }
            }.start();
            timerArray.put(helper.countDownTimer.hashCode(),helper.countDownTimer);

4.最后在activity的onDestroy方法里调用以下方法

@Override
    protected void onDestroy() {
        super.onDestroy();
        productAdapter.cancelAllTimers();
    }

cancelAllTimers方法如下

public void cancelAllTimers() {
        if (timerArray == null) {
            return;
        }
        int size = timerArray.size();
        for (int i = 0; i < size; i++) {
            CountDownTimer cdt = timerArray.get(timerArray.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }

这样刷新和滑动都不会造成混乱发生!

你可能感兴趣的:(CountDownTimer在recyclerview里造成的混乱问题的解决)