【发布时间】:2021-10-15 21:32:55
【问题描述】:
我一直在尝试 Jetpack Compose,但遇到了 LazyColumn 列表和 remember() 的问题。
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp{
MyScreen()
}
}
}
}
@Composable
fun MyApp(content: @Composable () -> Unit){
ComposeTestTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
content()
}
}
}
@Composable
fun MyScreen( names: List<String> = List(1000) {"Poofy #$it"}) {
NameList( names, Modifier.fillMaxHeight())
}
@Composable
fun NameList( names: List<String>, modifier: Modifier = Modifier ){
LazyColumn( modifier = modifier ){
items( items = names ) { name ->
val counter = remember{ mutableStateOf(0) }
Row(){
Text(text = "Hello $name")
Counter(
count = counter.value,
updateCount = { newCount -> counter.value = newCount } )
}
Divider(color = Color.Black)
}
}
}
@Composable
fun Counter(count: Int, updateCount: (Int) -> Unit) {
Button( onClick = {updateCount(count+1)} ){
Text("Clicked $count times")
}
}
这会运行并创建一个包含 1000 行的列表,其中每行显示“Hello Poofy #N”,然后是一个显示“Clicked N 次”的按钮。
一切正常,但如果我点击一个按钮来更新它的计数,当它滚出屏幕并重新打开时,计数将不会持续存在。
LazyColumn“回收”重新组合了行和计数。在上面的示例中,计数器被提升到NameList(),但我已经尝试在Counter() 中未提升它。两者都不起作用。
记住计数的正确方法是什么?我必须将它存储在活动中的数组中吗?
【问题讨论】:
标签: android kotlin android-jetpack-compose