Je sais comment créer un simple compte à rebours de 20 secondes en Java. Mais je voudrais créer celui-ci dans Kotlin.
package Android.os;
new CountDownTimer(20000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("Time's finished!");
}
}.start();
Comment puis-je le faire en utilisant Kotlin?
Si vous souhaitez afficher un compte à rebours avec jours heures minutes et secondes
private lateinit var countDownTimer:CountDownTimer
.
.
.
fun printDifferenceDateForHours() {
val currentTime = Calendar.getInstance().time
val endDateDay = "03/02/2020 21:00:00"
val format1 = SimpleDateFormat("dd/MM/yyyy hh:mm:ss",Locale.getDefault())
val endDate = format1.parse(endDateDay)
//milliseconds
var different = endDate.time - currentTime.time
countDownTimer = object : CountDownTimer(different, 1000) {
override fun onTick(millisUntilFinished: Long) {
var diff = millisUntilFinished
val secondsInMilli: Long = 1000
val minutesInMilli = secondsInMilli * 60
val hoursInMilli = minutesInMilli * 60
val daysInMilli = hoursInMilli * 24
val elapsedDays = diff / daysInMilli
diff %= daysInMilli
val elapsedHours = diff / hoursInMilli
diff %= hoursInMilli
val elapsedMinutes = diff / minutesInMilli
diff %= minutesInMilli
val elapsedSeconds = diff / secondsInMilli
txt_timeleft.text = "$elapsedDays days $elapsedHours hs $elapsedMinutes min $elapsedSeconds sec"
}
override fun onFinish() {
txt_timeleft.text = "done!"
}
}.start()
}
Si vous accédez à une autre activité/fragment, assurez-vous d'annuler le compte à rebours
countDownTimer.cancel()
Sortie de code
51 jours 17 hs 56 min 5 sec