Mode:
Duration:
1
Coding works best on desktop or with an external keyboard.
Coding works best on desktop or with an external keyboard.
Counter that automatically increments every second.
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import androidx.compose.runtime.LaunchedEffect
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AutoIncrementCounter()
}
}
}
@Composable
fun AutoIncrementCounter() {
var count by remember { mutableStateOf(0) }
var isRunning by remember { mutableStateOf(true) }
LaunchedEffect(Unit) {
while(true) {
delay(1000)
if(isRunning) count++
}
}
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text("Counter: $count", style = MaterialTheme.typography.h4)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = { isRunning = !isRunning }) { Text(if(isRunning) "Pause" else "Resume") }
Button(onClick = { count = 0 }) { Text("Reset") }
}
}
}Jetpack Compose is Android’s modern toolkit for building native UI using Kotlin, offering a declarative approach to designing app interfaces and simplifying UI development for Android.
Origin & Creator
Developed by Google and introduced in 2019 to modernize Android UI development with a declarative approach using Kotlin.
Industrial Note
Jetpack Compose is widely used for modern Android apps, enterprise applications, and apps that require dynamic UI updates and reactive components.