如何在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))
}
当两个+视图之间有如此多的共同点时,是时候将其移到单独的可组合文件中了。您可以指定参数中的所有差异,而不必为每个视图重复相同的设置。
我建议您为自定义文本字段创建状态类。我将存储文本、错误文本和验证器逻辑。所以你可以在需要时调用validate: on button click或on keyboard done button:
@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) }
)
}
}