kotlin语法remember使用记录
语法示例
1
2
3
4
|
var currentStep by remember {
mutableStateOf(1)
}
|
创建变量 currentStep 默认值为1
when使用记录
1
2
3
4
5
|
val description = when (currentStep) {
1 -> R.string.lemon_squeeze_title
else -> R.string.lemon_drink_description
}
|
当currentStep变量被更改之后,description的值也会随着变化
在composble中,我理解为是变量的绑定,组件中通过更改currentStep会导致对应的变量和相应的逻辑发生变化
完整的代码示例
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
@Composable
fun Lemon() {
var currentStep by remember {
mutableStateOf(1)
}
var squeezeCount by remember {
mutableStateOf(0)
}
val imageResource = when (currentStep) {
1 -> R.drawable.lemon_restart
else -> R.drawable.lemon_drink
}
val description = when (currentStep) {
1 -> R.string.lemon_squeeze_title
else -> R.string.lemon_drink_description
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
) {
Text(text = stringResource(description))
Spacer(modifier = Modifier.height(32.dp))
Button(
onClick = {
currentStep = when (currentStep) {
1 -> {
squeezeCount = (2..4).random()
2
}
2 -> {
squeezeCount--
if (squeezeCount == 0) {
3
} else {
2
}
}
3 -> 4
4 -> 1
else -> 1
}
},
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Magenta),
shape = RoundedCornerShape(40.dp)
) {
Image(
painter = painterResource(id = imageResource),
contentDescription = stringResource(description),
modifier = Modifier.wrapContentSize()
)
}
}
}
|