【问题标题】:How to show error message in OutlinedTextField in Jetpack Compose如何在 Jetpack Compose 的 OutlinedTextField 中显示错误消息
【发布时间】:2021-07-29 09:13:20
【问题描述】:

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

代码:

@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
    )
}

【问题讨论】:

    标签: android kotlin android-jetpack-compose


    【解决方案1】:

    撰写 1.0.x 不支持 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)
            )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 2022-07-06
      • 1970-01-01
      • 2021-12-15
      • 2022-11-04
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2022-12-25
      相关资源
      最近更新 更多