我正在学习如何使用 Jetpack Compose 开发 Android 应用程序,目前正在了解活动生命周期。我注意到一个意外的行为:我的
@Composable
函数是在 onResume
方法之后调用的,而不是在 onCreate
之后调用。
这是我的代码的相关部分:
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
)
}
}
}
}
在日志中,我看到以下序列:
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!
为什么在
@Composable
之后调用 onResume
函数,而不是在 onCreate
之后立即调用? UI不应该在调用onCreate
时在setContent
期间设置吗?
您的可组合项在需要在屏幕上显示时进行评估。直到
onResume()
之后才可以执行此操作,当 Activity 即将变得可见时会调用该函数。