設計中秋卡片應用程式,練習用Compose 使用輸入框數字來換圖片
使用remember 加到可組合項,可組合函式能夠將物件儲存在記憶體中。
在 remember 可組合項主體傳入 mutableStateOf() 函式。
var pictureInput by remember { mutableStateOf("") }
val choiceNumber = pictureInput.toIntOrNull() ?: 1
EditNumberField() 函式的內文中新增 TextField,用於接受設為空字串的 value 參數,以及設為空白 lambda 運算式的 onValueChange 參數
@Composable
fun EditNumberField(
value: String,
onValueChanged: (String) -> Unit,
modifier: Modifier
) {
TextField(
value = value,
singleLine = true,
modifier = modifier,
onValueChange = onValueChanged,
label = { Text("請輸入 1到6 圖片編號") },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
}
@Preview(showBackground = true)
@Composable
fun EditNumberFieldPreview() {
Ironman2024Theme {
EditNumberField("2",{},modifier = Modifier.padding(bottom = 32.dp).fillMaxWidth())
}
}
@Composable
fun Greeting(name: String, from: String, modifier: Modifier = Modifier) {
var result by remember { mutableStateOf(1) }
val imageResource = when (result) {
1 -> R.drawable.moon
2 -> R.drawable.moon_2
3 -> R.drawable.moon_3
4 -> R.drawable.moon_4
5 -> R.drawable.moon_5
else -> R.drawable.moon_6
}
var pictureInput by remember { mutableStateOf("") }
val choiceNumber = pictureInput.toIntOrNull() ?: 1
result = choiceNumber
Column(
verticalArrangement = Arrangement.Center,
modifier = modifier
) {
Box() {
GreenImage(imageResource)
Text(
text = name,
modifier = Modifier.align(Alignment.TopStart),
fontSize = 32.sp,
color = Color.White,
lineHeight = 116.sp,
textAlign = TextAlign.Center
)
Text(
text = from,
fontSize = 28.sp,
color = Color.White,
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp),
)
}
Text(text ="為您選擇第 ${result.toString()} 圖",
fontSize = 20.sp,
modifier= Modifier
.padding(16.dp)
.align(Alignment.CenterHorizontally),
)
EditNumberField(
value = pictureInput,
onValueChanged = { pictureInput = it },
modifier = Modifier.padding(bottom = 32.dp).fillMaxWidth()
)
}
}