2

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

AliSh
  • 10,085
  • 5
  • 44
  • 76
  • 1
    How user change it to text, if you only allowed numeric keyboard? You can change the keyboard type whenever you want. – commandiron Apr 28 '22 at 15:39
  • You have to do something like this, https://stackoverflow.com/a/14586341/9636037. Change the input type based on user selection. – Abhimanyu Apr 28 '22 at 16:57
  • That is not supported out-of-the-box by android. You'll need to create your own keyboard if you wish to implement this feature. There's no other way so I wouldn't recommend wasting your time looking for out-of-the-box solutions to your problem here. – Richard Onslow Roper Apr 28 '22 at 17:02

1 Answers1

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
                }
            )
        }
    }
)
AliSh
  • 10,085
  • 5
  • 44
  • 76