Dynamic Chronometer in Kotlin
Last Updated :
28 Mar, 2022
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:
- 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.
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.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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>
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.
XML
<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>
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 {...}
Kotlin
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()
}
})
}
}
AndroidManifest.xml file
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
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>
Run as Emulator:
Similar Reads
Android Architecture Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read
Android UI Layouts Layouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip
5 min read
MVVM (Model View ViewModel) Architecture Pattern in Android Developers always prefer clean and structured code for projects. Organizing the codes according to a design pattern helps in the maintenance of the software. By having knowledge of all crucial logic parts of the android application, it is easier to add and remove app features. Further, design patter
8 min read
Kotlin Android Tutorial Kotlin is a cross-platform programming language that may be used as an alternative to Java for Android App Development. Kotlin is an easy language so that you can create powerful applications immediately. Kotlin is much simpler for beginners to try as compared to Java, and this Kotlin Android Tutori
6 min read
Android Project folder Structure Android Studio is the official IDE (Integrated Development Environment) developed by the JetBrains community which is freely provided by Google for android app development. After completing the setup of Android Architecture we can create an android application in the studio. We need to create a new
3 min read
How to Install and Set up Android Studio on Windows | Step by Step Guide If you are starting your Android learning journey, Andriod Studio is the first thing you will install to write code on your system. This article will guide you on how to install and set up Android Studio on Windows 10, and 11 and what the actual Android Studio system requirements are. Quick Brief of
4 min read
Shared Preferences in Android with Example One of the most Interesting Data Storage options Android provides its users is Shared Preferences. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up you
7 min read
Bottom Navigation Bar in Android We all have come across apps that have a Bottom Navigation Bar. Some popular examples include Instagram, WhatsApp, etc. In this article, let's learn how to implement such a functional Bottom Navigation Bar in the Android app. Why do we need a Bottom Navigation Bar? It allows the user to switch to di
6 min read
Implicit and Explicit Intents in Android with Examples Pre-requisites: Android App Development Fundamentals for Beginners Guide to Install and Set up Android Studio Android | Starting with the first app/android project Android | Running your first Android app This article aims to tell about the Implicit and Explicit intents and how to use them in an and
6 min read