import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun CounterScreen() {
var counter by remember { mutableStateOf(0) }
Column(
modifier = Modifier.fillMaxSize().padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Counter: $counter", style = MaterialTheme.typography.headlineMedium)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { counter++ }) {
Text("Increase")
}
}
}
@Preview(showBackground = true)
@Composable
fun CounterScreenPreview() {
CounterScreen()
}We use remember with mutableStateOf to create a state variable counter that survives recompositions of the CounterScreen composable. The by keyword with var counter allows us to read and write the state value directly.
The Text composable shows the current value of counter. When the Button is clicked, we increase counter by 1. Because counter is a state, Compose automatically updates the UI to show the new value.
This pattern is common in Jetpack Compose to keep UI state simple and reactive.