如何在 Jetpack Compose 的 OutlinedTextField 中显示错误消息

时间:2021-07-29 09:13:20

标签: android kotlin android-jetpack-compose

我需要在 OutlinedTextField 中显示错误消息,但我没有找到任何有关如何执行此操作的文档。我在教程中找到了几种方法,例如创建带有提示的自定义输入字段或在输入字段下方创建文本,但它们很旧,也许有更好的方法。我需要显示这样的错误消息:

enter image description here

代码:

@Composable
fun EmailInputField(value: MutableState<String>, state: AuthState) {

    OutlinedTextField(
        value = value.value,
        onValueChange = { value.value = it },
        modifier = Modifier.fillMaxWidth(1f).height(60.dp),
        textStyle = TextStyle(color = Color.White),
        label = { Text(text = "Email", color = Color.White) },
        colors = TextFieldDefaults.outlinedTextFieldColors(
            focusedBorderColor = blue,
            unfocusedBorderColor = Color.White
        ),
        isError = state is AuthState.ValidationError,
        singleLine = true
    )
}

1 个答案:

答案 0 :(得分:2)

Compose 1.0.0 不支持 errorMessage 字段。

您可以使用以下内容:

var text by rememberSaveable { mutableStateOf("") }
var isError by rememberSaveable { mutableStateOf(false) }

fun validate(text: String) {
    isError = /* .... */
}

Column {
    TextField(
        value = text,
        onValueChange = {
            text = it
            isError = false
        },
        trailingIcon = {
            if (isError)
            Icon(Icons.Filled.Error,"error", tint = MaterialTheme.colors.error)
        },
        singleLine = true,
        isError = isError,
        keyboardActions = KeyboardActions { validate(text) },
    )
    if (isError) {
        Text(
            text = "Error message",
            color = MaterialTheme.colors.error,
            style = MaterialTheme.typography.caption,
            modifier = Modifier.padding(start = 16.dp)
        )
    }
}

enter image description here