VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/chronometer-in-kotlin/

⇱ Chronometer in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Chronometer in Kotlin

Last Updated : 7 Apr, 2025

Android ChronoMeter is user interface control which shows timer in the view. We can easily start up or down counter with base time using the chronometer widget. By default, start() method can assume base time and starts the counter.
Generally, we can create use ChronoMeter widget in XML layout but we can do it programmatically also.

Step by Step in Chronometer in Kotlin

Step 1: Create New Project

First we create a new project by following the below steps: 

  • Click on File, then New => New Project.
  • After that include the Kotlin support and click on next.
  • Select the minimum SDK as per convenience and click next button.
  • Then select the Empty activity => next => finish.

Step 2: Modify activity_main.xml file

In this file, we use the ChronoMeter widget along with a button to start or stop the meter and also set attributes for both of them.

Note:android:countDown is a attribute which is used to define whether the chronometer will count up or count down.

activity_main.xml:


Step 3: Update strings.xml file

Here, we update the name of the application using the string tag. We also other strings which can be used in MainActivity.kt file. 

MainActivity.kt:


Step 3: Access ChronoMeter in MainActivity.kt file

First, we declare a variable meter to access the Chronometer from the XML layout file. 

val meter = findViewById<Chronometer>(R.id.c_meter)

then, we access the button from the xml file and set setOnClickListener to start and stop the timer. 

val btn = findViewById<Button>(R.id.btn)
 btn?.setOnClickListener(object : View.OnClickListener {...}

MainActivity.kt:

Demo Video:


Comment
Article Tags:

Explore