How to make a Countdown Timer in Android using Kotlin

How to make a Countdown Timer in Android using Kotlin

Today, I will show you how to build a timer that countdowns until an event (e.g. new year’s day or release date of a video game) using the Handler to update the TextView every second.

First, add a TextView in your layout, like that:

Then go to your Activity and create a method with a name updateTime() and set the current date:

Set the event date

Find how many milliseconds left until the event

Convert the milliseconds to days, hours, minutes, and seconds

Show the countdown timer in your TextView

Now, to call the updateTime() method every second, we’re going to use the Handler() class and repeat the handler every second (1000 milliseconds)

If you want to show different text after the event has passed, create a method with a name endEvent and pass the currentdate and eventdate.

After you have shown your text, stop the handler from repeating.

Done!

You can find the final project here

If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!

Leave a Reply

avatar
  Subscribe  
Notify of

Follow me