Multiple count down timers in RecyclerView flickering when scrolled
As Andrei Lupsa said you should hold CountDownTimer reference in your ViewHolder, if you didn't want to timer reset when scrolling (onBindViewHolder) , you should check if CountDownTimer reference is null or not in onBindViewHolder :
public void onBindViewHolder(final FeedViewHolder holder, final int position) {
...
if (holder.timer == null) {
holder.timer = new CountDownTimer(expiryTime, 500) {
...
}.start();
}
}
public static class FeedViewHolder extends RecyclerView.ViewHolder {
...
CountDownTimer timer;
public FeedViewHolder(View itemView) {
....
}
}
This problem is simple.
RecyclerView
reuses the holders, calling bind each time to update the data in them.
Since you create a CountDownTimer
each time any data is bound, you will end up with multiple timers updating the same ViewHolder
.
The best thing here would be to move the CountDownTimer
in the FeedViewHolder
as a reference, cancel it before binding the data (if started) and rescheduling to the desired duration.
public void onBindViewHolder(final FeedViewHolder holder, final int position) { ... if (holder.timer != null) { holder.timer.cancel(); } holder.timer = new CountDownTimer(expiryTime, 500) { ... }.start(); } public static class FeedViewHolder extends RecyclerView.ViewHolder { ... CountDownTimer timer; public FeedViewHolder(View itemView) { ... } }
This way you will cancel any current timer instance for that ViewHolder
prior to starting another timer.