I have an input that for IDs that will, 99% of the time, be just numbers, so it's most comfortable for the user to have the numbers keyboard out. However sometimes they may need to include other characters so they need to be able to switch to the character keyboard.
The compose TextField offers the KeyboardOptions argument which in turn has a KeyboardType. However using KeyboardType.Number offers only the numbers keyboard, allowing for no variation, and I've had no luck finding any customizing settings to allow for variation.
I am defining the textfield as such:
TextField(
value = numberValue,
onValueChange = { numberValue = it },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
label = { Text("Number Keyboard Type") }
)
The KeyboardType
does not support setting a preferred input that can be toggled. You would need to implement a switching logic yourself to allow the user to switch the applied KeyboardType
.
A usual approach to do this would be by providing an IconButton
as trailingIcon
to the TextField
:
@Composable
fun TextNumberInput() {
var inputValue by remember { mutableStateOf(TextFieldValue("")) }
var inputNumeric by remember { mutableStateOf(true) }
TextField(
value = inputValue,
onValueChange = { inputValue = it },
keyboardOptions = KeyboardOptions(
keyboardType = if (inputNumeric) KeyboardType.Number else KeyboardType.Text
),
label = { Text((if (inputNumeric) "Number" else "Text") + " Keyboard Type") },
trailingIcon = {
IconButton(
onClick = {
inputNumeric = !inputNumeric
}
) {
Icon(
imageVector = if (inputNumeric) Icons.Filled.TextFields else Icons.Filled.Numbers,
contentDescription = "contentDescription"
)
}
}
)
}
The user then can toggle to an alphanumeric keyboard as needed. Note that keyboardType
alone does not restrict what the user can enter into the TextField
, they still can paste text or use an external keyboard even with KeyboardType.Number
. You would need to place such kind of validations to the onValueChange
callback, if needed.
Output: