单击按钮时 android 开发人员重构问题

问题描述 投票:0回答:1

我正在做这个练习来构建一个骰子应用程序

它有效,但我感到困惑的是: 根据我的理解,每次单击滚动按钮时,它都会触发重组。

当我点击滚动按钮时,它会随机选择 1 到 6 之间的一个数字。然后这个数字被记住,然后整个屏幕被重新组合?

那就是根据之前重构记住的结果来选择 imageResource 的时候?

然后通过图像渲染?

我的理解对吗?


@Composable
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) {
    var result by remember {mutableStateOf(1)}

    val imageResource = when (result) {
        1 -> R.drawable.dice_1
        2 -> R.drawable.dice_2
        3 -> R.drawable.dice_3
        4 -> R.drawable.dice_4
        5 -> R.drawable.dice_5
        else -> R.drawable.dice_6
    }
    Column( modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            painter = painterResource(imageResource),
            contentDescription = result.toString())
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = { result = (1..6).random()}) {
            Text(stringResource(R.string.roll))
            
        }

    }

}
android kotlin android-jetpack-compose
1个回答
0
投票

您的整体理解是正确的。然而,稍微但更深入地理解这个概念可能会很有用:

  • 您单击
    Button
    ,新的随机值将分配给
    result
    变量。
  • 您使用
    result
     声明了 
    mutableStateOf()
    变量。这允许 Jetpack Compose 检测您何时为变量分配新值并触发重组。
  • 依赖于
    result
    变量的可组合函数将使用新的
    result
    值进行重组。
  • 不依赖于
    result
    变量的可组合函数将 所有未使用
  • remember()
  • 持久化的变量都将被重置/重新计算。
    所有正常的 Kotlin 函数都将重新执行。
  • 您使用
  • result
     声明了 remember()
     变量。这确保了在重组过程中结果变量的值不会被重置。
  • 这些概念可以在以下示例中演示:

@Composable fun MyComposable() { var result by remember { mutableStateOf(1) } Column( horizontalAlignment = Alignment.CenterHorizontally ) { Button( onClick = { Log.d("MyComposable", "Dices are rolling...") result = (1..6).random() } ) { Text("ROLL") } Spacer(modifier = Modifier.weight(1f)) // Composable depends on result variable // will recompose when result variable is updated Text(text = "result: $result") // Composable does not depend on result variable, but has unstable parameter // will recompose whenever parent Composable recomposes Text(text = "randomResult: ${(7..12).random()}") // Composable does not depend on the result variable and has stable parameter // will not recompose when parent Composable recomposes Text(text = "some constant text") // normal Kotlin function // will be re-executed whenever parent Composable recomposes Log.d("MyComposable", "Dices are done") } }

每个
onClick

后的Logcat输出如下:

2024-04-29 10:38:29.122 10618-10618 MyComposable   D  Dices are rolling...
2024-04-29 10:38:29.137 10618-10618 MyComposable   D  Dices are done

© www.soinside.com 2019 - 2024. All rights reserved.