In material design TextField page TextField
has properties such as
Assistive elements provide additional detail about text entered into text fields.
Helper text Helper text conveys additional guidance about the input field, such as how it will be used. It should only take up a single line, being persistently visible or visible only on focus.
Error message When text input isn't accepted, an error message can display instructions on how to fix it. Error messages are displayed below the input line, replacing helper text until fixed.
Icons Icons can be used to message alerts as well. Pair them with error messages to provide redundant alerts, which are useful when you need to design for colorblind users.
Character counter Character or word counters should be used if there is a character or word limit. They display the ratio of characters used and the total character limit.
Do these properties exist for Jetpack Compose TextField
as of compose 1.0.0-alpha09
?
With 1.0.x
there aren't built-in properties to display an error message or the counter text.
However you can use a custom composable.
For the error message you can use something like:
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)
)
}
}
To display the counter text you can use something like:
val maxChar = 5
Column(){
TextField(
value = text,
onValueChange = {
if (it.length <= maxChar) text = it
},
modifier = Modifier.fillMaxWidth()
)
Text(
text = "${text.length} / $maxChar",
textAlign = TextAlign.End,
style = MaterialTheme.typography.caption,
modifier = Modifier.fillMaxWidth().padding(end = 16.dp)
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With