- Working with Countdown Timer in Android Studio Using Kotlin
- What is a countdown?
- How to implement the countdown timer from scratch using Kotlin on Android Studio
- 1. Start a new project on Android studio
- 2. Configure your Project
- 3. Lets design our view
- 5. Kotlin code for the Countdown Timer
- How to make a Countdown Timer in Android using Kotlin
- Kotlin Android CountDownTimer Examples
- Timer Examples
- Eample 1: Kotlin Android – Create a timer using CoundownTimer class
- Step 1: Dependencies
- Step 2: Design Layout
- Step 3: Write Code
- Reference
- Example 2: Create a timer using the Handler class
- Step 1: Dependencies
- Step 2: Create Layout
- Step 3: Write Code
- Example 3: How to create a recyclerveiw with multiple CountDownTimers
- Step 1: Create Project
- Step 2: Dependencies
- Step 3: Design Layouts
- Step 4: Create a Custom Runnable
- Step 5: Create a Custom Timer
- Step 6: Create a RecyclerView Adapter
- Step 7: Create main activity
- Reference
- Best timer libraries
- (a). Solution 1: Use TickingTimer
- Step 1: Install
- Step 2: How To Use?
- Customizations
- Saving Properties
- Example
- Reference
- Oclemy
Working with Countdown Timer in Android Studio Using Kotlin
Mar 7, 2020 · 6 min read
This tutorial shows you how to implement a countdown timer from scratch using android studio.
Before we dive into the whole technical aspect of this tutorial let’s try and understand what a countdown is or the need for a countdown timer.
What is a countdown?
A countdown is an act of counting down numerals in reverse o rder to zero. We all make use of countdown in our daily lives, is it when you and couple of friends are playing hide-and-seek or when you heat a delicious meal in the microwave or when Lebron James hit a clutch three pointer to win the championship as the clock winds down to 0.
There are lot of examples of times and moment we make use of countdown timers, the famous one we all know is at the launch of a rocket going to space or the countdown to a new year .
So we can see countdown timers are really important. Let get down to coding shall we.
How to implement the countdown timer from scratch using Kotlin on Android Studio
Before going ahead with this tutorial I’m assuming you having basic understanding of Kotlin programming and android studio.
Lets get to work!
1. Start a new project on Android studio
Select the empty activity so we would be able to create our own views
2. Configure your Project
You can name your app whatever like, i would be using CountdownApp
3. Lets design our view
Android development make use of the XML coding to design views for android apps.
So we are making use of the constraintlayout an EditText which takes our input, A TextView to display the progress of our timer and 2 Button to pause and cancel our Timer. Our second button is invisible because we want to only show that button whenever the timer is paused.
Now our app looks like this
5. Kotlin code for the Countdown Timer
Explanation of code
The Countdown timer package in android takes in time in milliseconds, so we had to convert our time to milliseconds and 1 minute equal to 60000 milliseconds.
start_mili_seconds initializes our timer text to start countdown from one minute in the absent of an inputted minute. The is_running variable helps us check if our timer is running so we are able to change the button text and also make the reset button visible whenever the is_running variable is true.
On click of the button that triggers the timer, we check if is_running is true we run the pauseTimer() function which changes the button text to pause and makes the reset button visible and also pause the timer, or else it takes the text from the EditText and converts it to a milliseconds and pass it as a parameter to the startTimer() function which then start our timer.
The startTimer() function consist of the whole logic we need to start our countdown, first we create a global variable:
which makes out CountDownTimer class available where we need it, now we need to initialize the countdown_timer
we make use of object declaration to initialize our CountDownTimer class which takes in 2 arguments:
- The time you intend to countdown in seconds and for us we named it as time_in_seconds
- The amount of time reduced in seconds, here we are using 1000 that’s per milliseconds reduce the time_in_seconds
It has two (2) implemented methods which are the onTick() and onFinish()
The onTick updates our UI text ( Textview) on the time remaining for the countdown to reach zero.
The updateTextUI() function converts our time_in_milliseconds and display it in actual minute and seconds so the user is able to understand and monitor the countdown timer.
Once the countdown is finished the onFinish() loads a confetti function which displays konfetti around the screen for successful completion of the countdown
To be able to use the Konfetti in your app you need to add this to your build.gradle file
and also add this to your MainActivity.kt file
Now that we have our countdown and konfetti. we want to be able to reset our timer when we want and that’s why we have the resetTimer() function
This function resets our timer back to 0 and hides the reset button so we start the timer all over again.
Источник
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.
If you have any questions, please feel free to leave a comment below
Источник
Kotlin Android CountDownTimer Examples
You can create a timer easily using classes like the Thread class and Handler class. Or if you want one with ready made UI then you can use a couple of libraries to inject a complete customizable timer. In this article, we want to look at how to create a timer using the aforementioned classes. We will also look at some ready made libraries to easen our work.
Questions this article helps answer
- How to create a timer easily in android.
- How to create a timer using handler.
- Best android timer libraries
Timer Examples
We will start by looking at examples of how to programmatically create a timer in android.
Eample 1: Kotlin Android – Create a timer using CoundownTimer class
This is an example written in Kotlin. A simple timer with features lik start, pause, reset is created. No special library is used. The CountDownTimer class defined in the android.os package is used.
Here is the demo of what is created:
Step 1: Dependencies
No special depdnency is needed for this project.
Step 2: Design Layout
The next step is to design your XML layout. In this example only a basic layout is designed. Simple widgets like textviews and buttons are what make up our timer.
activity_main.xml
Here is the layout:
Step 3: Write Code
The code is written in kotlin. For example the following function will define the Timer format:
This function on the other hand will reset the timer:
This other function will pause the timer:
While this function will start the timer:
Here is the full code:
Finally run the project.
Reference
Here is the code reference
No. | Link |
---|---|
1. | Download code |
2. | Browse code |
3. | Follow code author |
Example 2: Create a timer using the Handler class
Let’s look at how to create a timer using Handler class and textViews.
Step 1: Dependencies
No special dependency is needed.
Step 2: Create Layout
That layout will have a bunch of textviews to show various sections of our timer:
activity_main.xml
Step 3: Write Code
Next write java code;
Copy the above code and run it in android studio. Or download it form here. The code is written by this author.
Example 3: How to create a recyclerveiw with multiple CountDownTimers
This example has been created by the author as a solution for appropriately handling multiple countdown timers in a recyclerview in android. It is a solution that has been inspired by several questions in StackOverflow.Below are some of those questions;
Demo
Here are the demo screenshots of the final project:
Step 1: Create Project
Create an empty project in android studio.
Step 2: Dependencies
In this project butterknife is used for view binding. However this is not mandatory to the concept being taught and the library can be replaced or removed.
Step 3: Design Layouts
The two layouts needed are the recyclerview item layout and the main activity layout. The recyclerview item layout will contain an imageview and a textview next to it:
recycler_item.xml
The the main activity layout will contain the recyclerview.
activity_main.xml
Step 4: Create a Custom Runnable
Create a public class that implements the Runnable interface:
Define the instance properties of this class:
Define the constructor of this class, making it receive parameters values and assign them to the above instance properties:
Override the run() method and construct a timer with seconds,minutes, hours and days, and set the resultant string to the textview:
Here is the full code:
CustomRunnable.java
Step 5: Create a Custom Timer
It is a simple class with one Long property:
Step 6: Create a RecyclerView Adapter
A reyclerview needs an adapter to inflate the model layout into a View object and bind data to the inflated widgets. Here is the adapter able to handle the countdown timer;
RecyclerViewAdapter.java
Step 7: Create main activity
Finally put everything together in the only and launcher activity of this project:
MainActivity.java
Finally run the project.
Reference
Below are code references:
Number | Link |
---|---|
1. | Download code |
2. | Follow code author |
Best timer libraries
let’s now look at some third party libraries to create a timer.
(a). Solution 1: Use TickingTimer
TickingTimer is an Android Library to implement visual timer quickly, easily and effortlessly.
It’s features include:
- Kotlin First
- It is Highly Customizable.
- It is lifecycle aware.
- It provides animations support.
Here’s a demo:
Step 1: Install
- In the project-level build.gradle :
- In app-level build.gradle :
Step 2: How To Use?
- Add the timer in XML and specify width and height. TickingTimer currently doesn’t support feature-specific XML attributes.
- Start the timer in Java/Kotlin code:
Customizations
Function | Parameter(s) | Description |
---|---|---|
timerDuration() | duration (Int) | Duration for which timer should run |
backgroundTint() | color (Int?) | Colored tint for the background. If null is passed, tint is removed |
customBackground() | resource (@DrawableRes res: Int) | Custom background for the background provided as a drawable |
shape() | shape (Shape) | Set background shape from predefined: CIRCLE, ROUNDED and CIRCLE. Doesn’t apply if customBackground is applied after calling this function |
textSize() | size (Int) | Timer duration text size in sp (scaled-pixels) |
textColor() | color (Int) | Timer duration text color |
textAppearance() | resId (Int) | Use for custom styling of the text. Pass the style resource Id |
onFinished() | lambda () | Lambda callback executed when timer finishes |
onTick() | lambda (Int) | Lambda executed on every second elapsed and provides remaining time |
timerAnimation() | animation (Animation) | Custom timer animation |
timerEndAnimation() | lambda (View) | Lambda exposes View and is executed on timer end. Perform end animation on the view here |
applyConfig() | config (Config?) | Pass a config object to apply above properties in one go |
cancel() | N/A | Cancels the timer. Automatically gets called on onDestroy() of the activity/fragment |
Saving Properties
To save the properties of the timer to reuse, you can use a Config object. Create config like this:
and then apply to the timer while starting:
Another way to use the config is to use applyConfig() function:
Remember that the properties defined after applyConfig() overrides the config’s properties for the specific timer.
Example
Here’s a complete TickingTimer example:
MainActivity.kt
activity_main.xml
And here’s the layout:
Reference
Find complete reference here.
report this ad
Oclemy
Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .
Источник