1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| @Preview @Composable fun MyDemo() { var contents by remember { mutableStateOf(listOf("str1", "str0")) } Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { ElevatedButton(onClick = { val list = mutableListOf<String>() list.add("str${contents.size}") list.addAll(contents) contents = list }) { Text(text = "顶部插入") } for (txt in contents) { key(txt) { DemoText(text = txt) } } DemoText(text = "Hello1") DemoText(text = "Hello2") } }
@Composable fun DemoText(text: String) { Log.d("SecondActivity", "[rjy] DemoText=$text") Text(text = text) }
|
上述代码中,如果不使用key
,就会导致每次顶部插入时,for循环内部的组合项都会被重新构造。加上key
后,就会只构造text变化的DemoText。另外对于for循环外部的两个DemoText时不会重新构造的,因为这两个组合项的输入参数时不变的。
参考:可组合项的生命周期