60

I'd like to restrict what the user can type in a TextField in Jetpack Compose. How do I do that?

The equivalent in xml is inputType:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:hint="Only numbers please!" />
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Cristan
  • 12,083
  • 7
  • 65
  • 69

5 Answers5

108

Use KeyboardOptions:

TextField(
    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
Cristan
  • 12,083
  • 7
  • 65
  • 69
4

Ty like this KeyboardOptions

var textShopName by remember { mutableStateOf("") } 

OutlinedTextField(
            keyboardOptions = KeyboardOptions(
                capitalization = KeyboardCapitalization.None,
                autoCorrect = true,
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Next
            ),
            value = textShopName,
            onValueChange = { textShopName = it },
            label = { Text("Shop Name") },
            modifier = Modifier
                .padding(start = 16.dp, end = 16.dp, top = 20.dp)
                .fillMaxWidth(),

            )
Livin
  • 166
  • 3
  • 8
3

For Password keyboard type for hiding password you have to set the visualTransformation too

TextField(
 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
 visualTransformation =  PasswordVisualTransformation(),
                
Manohar
  • 22,116
  • 9
  • 108
  • 144
2

You can use something like:

TextField(
        ....,
        keyboardOptions = 
             KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number)
        )
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
1

Just to add to the answers above if you want to show numeric keyboard for decimal numbers keep in mind that:

Most keyboards show a decimal separator when keyboard type is set as Number. However, it is possible that a keyboard expects TYPE_NUMBER_FLAG_DECIMAL flag in inputType to actually show a key for decimal separator.

So if you want to show numeric keyboard for decimal numbers in order to avoid corner cases in certain keyboards you should use keyboardType = KeyboardType.Decimal:

TextField(
        ...,
        keyboardOptions = 
             KeyboardOptions(keyboardType = KeyboardType.Decimal)
        ...,    
        )
F.Mysir
  • 2,838
  • 28
  • 39
  • Inside the Code found `androidx.compose.ui.text.input.KeyboardType` "A keyboard type used to request an IME that is capable of inputting decimals. IME should explicitly provide a decimal separator as input, which is not assured by KeyboardType.Number." – CryptoCode Jan 28 '23 at 16:56