Cristan
Cristan

Reputation: 14095

How to set the inputType for a TextField in Jetpack Compose

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!" />

Upvotes: 81

Views: 36348

Answers (5)

F.Mysir
F.Mysir

Reputation: 4166

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)
        ...,    
        )

Upvotes: 3

Manohar
Manohar

Reputation: 23394

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

TextField(
 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
 visualTransformation =  PasswordVisualTransformation(),
                

Upvotes: 4

Cristan
Cristan

Reputation: 14095

Use KeyboardOptions:

TextField(
    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)

Upvotes: 133

Livin
Livin

Reputation: 326

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(),

            )

Upvotes: 8

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363975

You can use something like:

TextField(
        ....,
        keyboardOptions = 
             KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number)
        )

Upvotes: 2

Related Questions