美文网首页
CountDownTimer在recyclerview里造成的混

CountDownTimer在recyclerview里造成的混

作者: 不等离子 | 来源:发表于2018-06-20 18:04 被阅读0次

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<CountDownTimer> timerArray;
    public ProductAdapter(int layoutResId, @Nullable List<StakingProduct> 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里造成的混

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