使用值/状态时的 Android 可组合重构计时

Android composable re-compose timing when using value/state

提问人:Jeff Lin 提问时间:9/26/2023 更新时间:9/26/2023 访问量:22

问:

我测试了下面的代码,但是每次我输入 textField 时都会重新组合(每次我输入 textField 时记录显示 2)

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    ComposePracticeTheme {
        HomeSection(modifier = Modifier)
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeSection(
    modifier: Modifier = Modifier,
) {
    var input by remember { mutableStateOf("") }
    val isGreen by remember { derivedStateOf(){input.length>5} }
    Log.d("MainActivity", "1");
    Scaffold {paddingValues ->
        Content(modifier = modifier.padding(paddingValues), input = input, isGreen = isGreen, onChange = {input = it})
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchBar(modifier: Modifier, input:String, onChange: (String)->Unit) {
    Surface(modifier = Modifier.padding(8.dp)) {
        TextField(value = input, onValueChange = onChange, modifier = modifier
            .fillMaxWidth()
            .heightIn(min = 56.dp),
            leadingIcon = {
                Icon(painter = painterResource(id = R.drawable.ic_launcher_foreground), contentDescription = "",
                    tint = Color.Unspecified)
            })
    }
}

@Composable
fun Content(modifier: Modifier, input: String, isGreen: Boolean, onChange: (String) -> Unit){
    Log.d("MainActivity", "2");
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        SearchBar(modifier,input, onChange)
        Text(text = if(isGreen)"is Green" else "is Blue", color = if(isGreen) Color.Green else Color.Blue)
    }
}

但如果我改变

var input by remember { mutableStateOf("") }
val isGreen by remember { derivedStateOf(){input.length>5} }

var input = remember { mutableStateOf("") }
val isGreen = remember { derivedStateOf(){input.value.length>5} }

它只有在 isGreen 更改状态时才会重组,为什么使用 value/State 会导致不同的行为?

人造人 可组合

评论

0赞 Vivek Gupta 9/26/2023
val isGreen by remember { derivedStateOf(){input.length>5} }。这里 derivedState 作为输入字段更改没有用,变量 isGreen 也需要更新(因为没有什么可以缓冲的),只需使用 val isGreen = input.length >5

答: 暂无答案