'Compose TextField with number keypad by default, but allowing alphabetic characters

I want to show a numeric keyboard by default but let the user change it to text.

var text by rememberSaveable { mutableStateOf("") }
TextField(
    value = text,
    onValueChange = { text = it },
    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)

I read a lot of old questions and answers but none of them were helpful, including:

How do I default to numeric keyboard on EditText without forcing numeric input?

EditText with number keypad by default, but allowing alphabetic characters



Solution 1:[1]

There is no straightforward solution. So, I decided to implement it myself:

var keyboardType by remember { mutableStateOf(KeyboardType.Number) }
var text by rememberSaveable { mutableStateOf("") }
TextField(
    value = text,
    onValueChange = { text = it },
    keyboardOptions = KeyboardOptions.Default.copy(keyboardType = keyboardType),
    trailingIcon = {
        if (keyboardType == KeyboardType.Number) {
            Icon(
                painterResource(
                    id = if (keyboardType == KeyboardType.Number)
                        R.drawable.ic_abc_24
                    else
                        R.drawable.ic_pin_24
                ),
                contentDescription = "Change keyboard",
                modifier = Modifier.clickable {
                    keyboardType = if (keyboardType == KeyboardType.Number)
                        KeyboardType.Text
                    else
                        KeyboardType.Number
                }
            )
        }
    }
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AliSh