override fun onCreate(savedInstanceState: Bundle?) { supportActionBar?.hide() super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) setContent { TestComposeTheme { var state = false Log.e("StateDemoActivity", "hashcode:${state.hashCode()} value:${state}") Column(modifier = Modifier.fillMaxSize().systemBarsPadding()) { Button(onClick = { state = !state Log.e("StateDemoActivity", "onClick hashcode:${state.hashCode()} value:${state}") }, modifier = Modifier.fillMaxWidth()) { Text( text = "Change State:${state}", color = MyColorTheme.textMain, fontSize = 20.sp ) } } } } } }
对应输出如下:
1 2 3 4 5
StateDemoActivity E hashcode:1237 value:false StateDemoActivity E onClick hashcode:1231 value:true StateDemoActivity E onClick hashcode:1237 value:false StateDemoActivity E onClick hashcode:1231 value:true StateDemoActivity E onClick hashcode:1237 value:false
StateDemoActivity E hashcode:103910553 value:false StateDemoActivity E onClick hashcode:103910553 value:true StateDemoActivity E hashcode:118168247 value:false StateDemoActivity E onClick hashcode:118168247 value:true StateDemoActivity E hashcode:245965755 value:false
StateDemoActivity E hashcode:103910553 value:false StateDemoActivity E onClick hashcode:103910553 value:true StateDemoActivity E hashcode:103910553 value:true StateDemoActivity E onClick hashcode:103910553 value:false StateDemoActivity E hashcode:103910553 value:false
remember方法内部必然有全局容器存储变量,源码中可以很明显的看出
1 2 3
@Composable inline fun <T> remember(crossinline calculation: @DisallowComposableCalls () -> T): T = currentComposer.cache(false, calculation)