kotlin android app development course, creating the stopwatch feature of a clock app

Implementing a stopwatch feature while creating a clock app in Android development is a very useful exercise. In this article, we will detail how to create a stopwatch feature using Kotlin. We will set up the overall app structure, design the UI of the stopwatch, and implement its basic functionality.

1. Project Setup

Open Android Studio and create a new project. Set the project name to “StopwatchApp” and choose Kotlin as the language. Set the Minimum SDK to API 21 (Lollipop) or higher.

1.1. Adding Gradle Dependencies

No special libraries are needed to implement the UI elements of the stopwatch, but we will use ViewModel and LiveData to manage the UI state. Therefore, add the following dependencies to the build.gradle file.

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.4.0"

2. UI Design

The UI of the stopwatch consists mainly of TextView and Button. Open the activity_main.xml file and design the UI as follows.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <TextView
        android:id="@+id/tvStopwatch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="48sp"
        android:text="00:00:00"
        android:layout_marginBottom="20dp"/>

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start"/>

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop"/>

    <Button
        android:id="@+id/btnReset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reset"/>

</LinearLayout>

3. Implementing Logic

Open the MainActivity.kt file and implement the logic of the stopwatch. We will utilize CountDownTimer to count the time of the stopwatch.

3.1. Creating ViewModel

Create a ViewModel class to manage the state of the stopwatch. This will allow us to store UI-related data.

class StopwatchViewModel : ViewModel() {
    private var timer: CountDownTimer? = null
    private var time = 0L
    private val _formattedTime = MutableLiveData()

    val formattedTime: LiveData get() = _formattedTime

    private fun updateTime() {
        val hours = (time / 3600000) % 24
        val minutes = (time / 60000) % 60
        val seconds = (time / 1000) % 60
        _formattedTime.value = String.format("%02d:%02d:%02d", hours, minutes, seconds)
    }

    fun start() {
        timer = object : CountDownTimer(Long.MAX_VALUE, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                time += 1000
                updateTime()
            }

            override fun onFinish() {}
        }.start()
    }

    fun stop() {
        timer?.cancel()
    }

    fun reset() {
        stop()
        time = 0
        updateTime()
    }
}

3.2. Implementing MainActivity

Now, in the MainActivity.kt file, we will handle button click events using the ViewModel.

class MainActivity : AppCompatActivity() {
    private lateinit var viewModel: StopwatchViewModel
    private lateinit var tvStopwatch: TextView
    private lateinit var btnStart: Button
    private lateinit var btnStop: Button
    private lateinit var btnReset: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModel = ViewModelProvider(this).get(StopwatchViewModel::class.java)
        tvStopwatch = findViewById(R.id.tvStopwatch)
        btnStart = findViewById(R.id.btnStart)
        btnStop = findViewById(R.id.btnStop)
        btnReset = findViewById(R.id.btnReset)

        viewModel.formattedTime.observe(this, { time ->
            tvStopwatch.text = time
        })

        btnStart.setOnClickListener {
            viewModel.start()
        }

        btnStop.setOnClickListener {
            viewModel.stop()
        }

        btnReset.setOnClickListener {
            viewModel.reset()
        }
    }
}

4. Running and Testing the App

Now let’s run the app and test the stopwatch feature. Pressing the start button will start the stopwatch, the stop button will halt the time, and the reset button will reset the time.

5. Improvements

While the basic stopwatch functionality is implemented, the following additional features can be improved and implemented:

  • Add a Pause feature
  • Add a Lap feature
  • Improve the UI and apply animations

6. Conclusion

In this article, we explained how to create a simple stopwatch feature in an Android app using Kotlin. Through this basic app, you will familiarize yourself with fundamental concepts of Kotlin and Android. It will serve as a strong foundation for building more complex apps in the future.

Now, as you develop each feature further, enhance your Android app development skills!