Coding Bihar

Stopwatch in Jetpack Compose

Stopwatch in Jetpack Compose - Coding Bihar
Stopwatch in Jetpack Compose
A stopwatch is like a timekeeper’s personal assistant, designed specifically to measure the duration of an event with precision. It’s not just about counting seconds; it’s a tool for capturing moments, whether it’s timing a runner’s sprint, tracking a cooking experiment, or pacing yourself during a workout. Imagine it as a digital or analog device that transforms time into data, allowing you to dissect every fleeting second into actionable insights. In a world where every second counts, a stopwatch becomes your ally in mastering moments.

We can build a simple stopwatch in Jetpack Compose using LaunchedEffect, remember, and State to track time.

Step 1: Set Up the Project

First, create a new Android project in Android Studio and choose Jetpack Compose as the UI toolkit.

Step 2: Create the Stopwatch Composable Function

In the MainActivity.kt file, let's begin by building the Stopwatch Composable. We will use State variables to manage the running state of the stopwatch and to keep track of time.

Create a StopwatchApp composable function:

Open your MainActivity.kt and replace the content of setContent with your custom composable StopwatchApp.
Stopwatch in Jetpack Compose OutputStopwatch in Jetpack Compose Output 2

MainActivity

Copy this code →

package com.codingbihar.myapplication

import ...

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MyApplicationTheme {
                StopwatchApp()
                
        }
    }
}
Copy this code →

StopwatchApp


package com.codingbihar.myapplication

import ...

@Composable
fun StopwatchApp() {
    var isRunning by remember { mutableStateOf(false) }
    var seconds by remember { mutableIntStateOf(0) }

    if (isRunning) {
        LaunchedEffect(Unit) {
            while (true) {
                delay(1000)  // Delay for 1 second
                seconds++
            }
        }
    }

    // UI layout
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black)
            .padding(16.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = formatTime(seconds),
                color = Color.Green,
                fontSize = 48.sp
            )
            Spacer(modifier = Modifier.height(20.dp))
            Row {
                Button(onClick = { isRunning = true }) {
                    Text("Start")
                }
                Spacer(modifier = Modifier.width(10.dp))
                Button(onClick = { isRunning = false }) {
                    Text("Stop")
                }
                Spacer(modifier = Modifier.width(10.dp))
                Button(onClick = {
                    isRunning = false
                    seconds = 0
                }) {
                    Text("Reset")
                }
            }
        }
    }
}

// Format seconds to MM:SS
fun formatTime(seconds: Int): String {
    val minutes = seconds / 60
    val remainingSeconds = seconds % 60
    return String.format(Locale.getDefault(), "%02d:%02d", minutes, remainingSeconds)
}
 Sandeep Gupta

Posted by Sandeep Gupta

Please share your feedback us at:sandeep@codingbihar.com. Thank you for being a part of our community!

Special Message

Welcome to coding bihar!