I have a Recyclerview
, and I need to display a countdown on every row.
Here is a similar question coutndown timers in listview It has a good solution ,
After 6 hours I finally found how to use it. However, I couldn't find the same way with the Runnable.
I'm using this code and it works for me:
@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date event_date = dateFormat.parse(laterStart.toString());
current_date = dateFormat.parse(laterCurrent.toString());
Date diff = event_date.getTime() - current_date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
//Very important code for some problems
if (holder.timer != null) {
holder.timer.cancel();
}
holder.timer = new CountDownTimer(diff, 900) {
@Override
public void onTick(long millisUntilFinished) {
long day = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
millisUntilFinished -= TimeUnit.DAYS.toMillis(day);
long hour = TimeUnit.MILLISECONDS.toHours(millisUntilFinished);
millisUntilFinished -= TimeUnit.HOURS.toMillis(hour);
long minute = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished);
millisUntilFinished -= TimeUnit.MINUTES.toMillis(minute);
long second = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);
holder.timeText.setText(day+":"+hour+":"+minute+":"+second);
}
@Override
public void onFinish() {
}
}.start();
}
And RecycleView ViewHolder class:
public class ViewHolder extends RecyclerView.ViewHolder {
***your codes***
//Just add CountDownTimer
CountDownTimer timer;
*** your codes ***
}