那里!
我正在使用 Jetpack Compose 编写 BMI 计算器。 我设置了两个“TextFieldValue”函数来输入用户的身高和体重。这两个函数都返回“文本”,我无法将其转换为 Double 类型,因此我可以进行数学运算!
我坚持了3个多小时! 我开始从事 Android 开发,因此非常感谢您的帮助! 嗯,非常感谢!
我试过:
// Insert function:
fun insertWeight (): TextFieldValue {
var text by remember {
mutableStateOf(TextFieldValue(""))
}
TextField(
value = text,
onValueChange = {
text = it
},
label = {
Text (text = "Weight")
},
placeholder = {
Text (text = "Insert your weight in Kilograms")
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
return text
}
然后(在 MainActivity 中)
// I couldn't find out how to do it directly without passing by String (I even don't know if it is right"
val weight: Double = insertWeight().toString().toDouble()
我也试过另一种东西,将函数类型从“TextFieldValue”更改为“Double”,然后将函数中的返回更改为“return text.toString().toDouble()”,然后我意识到这是一个非常愚蠢的尝试 hahahaha 如果类型不匹配,compose 函数将致命地终止应用程序!
你不能在普通函数中使用
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)
)
}
输出