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();
}
}
}
这样刷新和滑动都不会造成混乱发生!