I'm learning how to develop an Android app using Jetpack Compose, and I'm currently working through understanding the activity lifecycle. I noticed an unexpected behavior: my @Composable
function is being called after the onResume
method, instead of right after onCreate
.
Here is the relevant part of my code:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.i("LifeCycle", "We are in onCreate!")
enableEdgeToEdge()
setContent {
ContatoreApp()
}
}
override fun onStart() {
super.onStart()
Log.i("LifeCycle", "We are in onStart!")
}
override fun onResume() {
super.onResume()
Log.i("LifeCycle", "We are in onResume!")
}
override fun onPause() {
super.onPause()
Log.i("LifeCycle", "We are in onPause!")
}
override fun onStop() {
super.onStop()
Log.i("LifeCycle", "We are in onStop!")
}
override fun onRestart() {
super.onRestart()
Log.i("LifeCycle", "We are in onRestart!")
}
override fun onDestroy() {
Log.i("LifeCycle", "We are in onDestroy!")
super.onDestroy()
}
}
@Composable
fun ContatoreApp() {
Log.i("LifeCycle", "We are creating the UI!")
var value by remember { mutableIntStateOf(0) }
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Column(
modifier = Modifier
.padding(innerPadding)
.fillMaxSize(),
verticalArrangement = Arrangement.SpaceEvenly,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(R.string.contatore, value),
fontSize = 30.sp
)
Button(onClick = { value++ }) {
Text(
text = stringResource(R.string.incrementa),
modifier = Modifier.padding(10.dp),
fontSize = 30.sp
)
}
}
}
}
In the logs, I see the following sequence:
2024-07-12 16:16:57.970 30565-30565 LifeCycle I We are in onCreate!
2024-07-12 16:16:58.146 30565-30565 LifeCycle I We are in onStart!
2024-07-12 16:16:58.151 30565-30565 LifeCycle I We are in onResume!
2024-07-12 16:16:58.819 30565-30565 LifeCycle I We are creating the UI!
Why is the @Composable
function being called after onResume
instead of immediately after onCreate
? Shouldn't the UI be set up during onCreate
when setContent
is called?
Your Composable is evaluated when it’s time to display it on screen. It’s not time to do that until afteronResume()
, which is called when an Activity is about to become visible.