如何在 Jetpack Compose 中为多个文本字段显示错误消息

3
如何在Jetpack Compose中为多个TextField显示错误消息。只需要一个字段:
private var isError by mutableStateOf(false)

private fun validate(text: String){
    isError = if(text.isEmpty()){
        true
    }else{
        android.util.Patterns.EMAIL_ADDRESS.matcher(text).matches()
    }

    Log.i("Boolean",isError.toString())

}

    TextField(value = email,placeholder = { Text(text = "E-mail")},
            onValueChange = {
                email=it
                isError = false
            },
            shape = RoundedCornerShape(8.dp),
            colors = TextFieldDefaults.textFieldColors(
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent,
                    disabledIndicatorColor = Color.Transparent

            ),
            singleLine = true,
            isError = isError,
            keyboardActions = KeyboardActions { validate(email) },
            modifier=Modifier.align(Alignment.CenterHorizontally),
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
            leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = null) })

我有一个表单,其中有很多TextField,如何逐个验证。例如,如果我有两个字段名称和电子邮件。 我考虑使用循环遍历所有字段,但我不知道这是否是最佳实践。 有人可以帮我吗?

    var nome by rememberSaveable{ mutableStateOf("")}
    var email by rememberSaveable{ mutableStateOf("") }

       

 TextField(value = nome,placeholder = { Text(text = "Nome")},
                onValueChange = {
                    nome=it
                },
                shape = RoundedCornerShape(8.dp),
                colors = TextFieldDefaults.textFieldColors(
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        disabledIndicatorColor = Color.Transparent

                ),
                modifier=Modifier.align(Alignment.CenterHorizontally),
                leadingIcon = { Icon(imageVector = Icons.Default.Person, contentDescription = null) })

        Spacer(modifier = Modifier.padding(5.dp))


        TextField(value = email,placeholder = { Text(text = "E-mail")},
                onValueChange = {
                    email=it
                   
                },
                shape = RoundedCornerShape(8.dp),
                colors = TextFieldDefaults.textFieldColors(
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent,
                        disabledIndicatorColor = Color.Transparent

                ),
                modifier=Modifier.align(Alignment.CenterHorizontally),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
                leadingIcon = { Icon(imageVector = Icons.Default.Email, contentDescription = null) })

    Spacer(modifier = Modifier.padding(5.dp))


    Button(
            onClick = { verifyEmpty(strings=validate) },
            colors = ButtonDefaults.buttonColors(
                    contentColor = colorResource(id = R.color.marron),
                    backgroundColor = colorResource (id = R.color.pastel_green)
            ),
    ) {
        Text(text = stringResource(id = R.string.view_cad),
                color= colorResource(id = R.color.marron))
    }
1个回答

4

当两个或多个视图之间有很多共同点时,可以将它们移动到一个单独的可组合项中。您可以在参数中指定所有不同之处,而不是为每个视图重复相同的设置。

我建议您为自定义文本字段创建状态类。我会存储文本、错误文本和验证逻辑。这样,您可以在需要时调用验证:在按钮单击或键盘完成按钮上:

@Composable
fun TestView(
) {
    val nomeState = rememberErrorTextFieldState("", validate = { text ->
        when {
            text.isEmpty() -> {
                "text.isEmpty()"
            }
            else -> null
        }
    })
    val emailState = rememberErrorTextFieldState("", validate = { text ->
        when {
            text.isEmpty() -> {
                "text.isEmpty()"
            }
            !android.util.Patterns.EMAIL_ADDRESS.matcher(text).matches() -> {
                "pattern doesn't match"
            }
            else -> null
        }
    })

    Column {
        ErrorTextField(
            state = nomeState,
            placeholderText = "nome",
            leadingIconVector = Icons.Default.Person,
            modifier = Modifier.align(Alignment.CenterHorizontally),
        )
        ErrorTextField(
            state = emailState,
            placeholderText = "email",
            leadingIconVector = Icons.Default.Email,
            modifier = Modifier.align(Alignment.CenterHorizontally),
        )
        Button(
            onClick = {
                listOf(nomeState, emailState).forEach(ErrorTextFieldState::validate)
            },
        ) {
            Text(text = "stringResource(id = R.string.view_cad)")
        }
    }
}


@Composable
fun ErrorTextField(
    state: ErrorTextFieldState,
    placeholderText: String,
    leadingIconVector: ImageVector,
    modifier: Modifier,
) {
    Column {
        val error = state.error
        TextField(
            value = state.text,
            onValueChange = { state.updateText(it) },
            placeholder = { Text(text = placeholderText) },
            shape = RoundedCornerShape(8.dp),
            colors = TextFieldDefaults.textFieldColors(
                focusedIndicatorColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                disabledIndicatorColor = Color.Transparent,
                errorCursorColor = Color.Red
            ),
            singleLine = true,
            isError = error != null,
            leadingIcon = { Icon(imageVector = leadingIconVector, contentDescription = null) },
            keyboardActions = KeyboardActions {
                state.validate()
            },
            modifier = modifier,
        )
        if (error != null) {
            Text(
                error,
                color = Color.Red,
            )
        }
    }
}

@Composable
fun rememberErrorTextFieldState(
    initialText: String,
    validate: (String) -> String? = { null },
): ErrorTextFieldState {
    return rememberSaveable(saver = ErrorTextFieldState.Saver(validate)) {
        ErrorTextFieldState(initialText, validate)
    }
}

class ErrorTextFieldState(
    initialText: String,
    private val validator: (String) -> String?,
) {
    var text by mutableStateOf(initialText)
        private set

    var error by mutableStateOf<String?>(null)
        private set

    fun updateText(newValue: String) {
        text = newValue
        error = null
    }

    fun validate() {
        error = validator(text)
    }

    companion object {
        fun Saver(
            validate: (String) -> String?,
        ) = androidx.compose.runtime.saveable.Saver<ErrorTextFieldState, String>(
            save = { it.text },
            restore = { ErrorTextFieldState(it, validate) }
        )
    }
}

我按照你的示例操作了,但错误如何显示?或者只需将isError设置为false或true吗?我正在使用compose_version ='1.0.0-rc01'。 - Rafael Souza
当我在文本框中点击回车时,如果出现错误,它会使用以下代码显示错误消息: if(isError){ Text(text = "error message") } 但是当我点击按钮时,它是如何工作的? - Rafael Souza
@RafaelSouza 我没有注意到你需要那个按钮,我已经更新了我的答案。另外,你可以升级到“1.0.1”,它在一段时间前发布了。 - Phil Dukhov
嗨菲利普,Saver函数出现了以下错误:类型检查遇到了递归问题。最简单的解决方法是显式指定您的声明类型 - Stefano Sansone
1
@StefanoSansone 可能自那时起有些事情已经改变了 =) 我已经更新了我的答案。 - Phil Dukhov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接