您不能使用
composable function
在正常函数中,或者不能返回数据(因为可组合函数不是正常函数,它是一个小部件或Ui),您可以从下面的代码中实现上述内容。希望它能帮助你。
@Composable
fun TextFieldValueScreen() {
var weight by remember { mutableStateOf("") }
var height by remember { mutableStateOf("") }
var total by remember { mutableStateOf(0.0) }
val context = LocalContext.current
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
CommonTextField(
title = "Weight",
placeholder = "Insert your weight in Kilograms",
text = weight,
onValueChange = { weight = it }
)
Spacer(modifier = Modifier.height(20.dp))
CommonTextField(
title = "Height",
placeholder = "Insert your height in meter",
text = height,
onValueChange = { height = it }
)
Spacer(modifier = Modifier.height(20.dp))
Button(onClick = {
if (height.isNotEmpty() && weight.isNotEmpty()) {
total = (weight.toDouble()) / (height.toDouble() * height.toDouble())
} else {
Toast.makeText(context, "Please type height and weight", Toast.LENGTH_SHORT).show()
}
}) {
Text(text = "Calculate")
}
Spacer(modifier = Modifier.height(20.dp))
if (total != 0.0)
Text(
text = "BMI is ${String.format(Locale.US, "%.2f", total)}",
style = TextStyle(
fontSize = 25.sp,
fontWeight = FontWeight.SemiBold,
fontStyle = FontStyle.Italic,
)
)
}
}
@Composable
fun CommonTextField(
title: String,
placeholder: String,
text: String,
onValueChange: (String) -> Unit
) {
TextField(
value = text,
onValueChange = onValueChange,
label = {
Text(text = title)
},
placeholder = {
Text(text = placeholder)
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone)
)
}
输出