Dynamic Chronometer in Kotlin

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.

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



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

Modify activity_main.xml file

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/constraint_layout">
  
  
    <LinearLayout
        android:id="@+id/l_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    </LinearLayout>
  
  
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="163dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="163dp"
        android:text="@string/start"
        app:layout_constraintEnd_toEndOf="@id/l_layout"
        app:layout_constraintHorizontal_bias="0.485"
        app:layout_constraintStart_toEndOf="@+id/l_layout"
        app:layout_constraintStart_toStartOf="@id/l_layout"
        app:layout_constraintTop_toBottomOf="@+id/l_layout" />
  
</androidx.constraintlayout.widget.ConstraintLayout>

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<resources>
    <string name="app_name">ChronometerInKotlin</string>
    <string name="stop">Stop Timer</string>
    <string name="start">Start Timer</string>
    <string name="working">Started</string>
    <string name="stopped">Stopped</string>
</resources>

chevron_right


Create ChronoMeter in MainActivity.kt file

First, we declare a variable meter to create the Chronometer in Kotlin file.

val meter = Chronometer(this)
        // set color and size of the text
        meter.setTextColor(Color.BLUE)
        meter.setTextSize(TypedValue.COMPLEX_UNIT_IN,0.25f)

also, add the chronometer in layout using

val linearLayout = findViewById(R.id.l_layout)
        linearLayout?.addView(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 {...}
filter_none

edit
close

play_arrow

link
brightness_4
code

package com.geeksforgeeks.myfirstkotlinapp
  
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
  
import android.os.Bundle
import android.util.TypedValue
import android.widget.Button
import android.view.View
import android.view.ViewGroup
import android.widget.Chronometer
import android.widget.LinearLayout
import android.widget.Toast
  
class MainActivity : AppCompatActivity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // create the chronometer from XML file
        val meter = Chronometer(this)
        // set color and size of the text
        meter.setTextColor(Color.BLUE)
        meter.setTextSize(TypedValue.COMPLEX_UNIT_IN,0.25f)
  
  
        val layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT)
        layoutParams.setMargins(30, 40, 120, 40)
        meter.layoutParams = layoutParams
  
  
  
        val linearLayout = findViewById<LinearLayout>(R.id.l_layout)
        linearLayout?.addView(meter)
  
        //access the button using id
        val btn = findViewById<Button>(R.id.btn)
        btn?.setOnClickListener(object : View.OnClickListener {
  
            var isWorking = false
  
            override fun onClick(v: View) {
                if (!isWorking) {
                    meter.start()
                    isWorking = true
                } else {
                    meter.stop()
                    isWorking = false
                }
  
                btn.setText(if (isWorking) R.string.start else R.string.stop)
  
                Toast.makeText(this@MainActivity, getString(
                    if (isWorking)
                        R.string.working
                    else
                        R.string.stopped),
                    Toast.LENGTH_SHORT).show()
            }
        })
    }
}

chevron_right


AndroidManifest.xml file

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
package="com.geeksforgeeks.myfirstkotlinapp">
  
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
  
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
  
</manifest>

chevron_right


Run as Emulator:

 



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.