How to add Password TextField in Android Jetpack Compose

By Mohammed Rashid •  September 1st, 2022 • 

A TextField composable helps to add text input in Jetpack Compose. The same composable can be used to type in passwords. In this Jetpack Compose tutorial let’s check how to add TextField to enter passwords.

TextField composable has a parameter named KeyboardOptions that helps to change input types. You also have to set visualTransformation as PasswordVisualTransformation. See the code snippet given below.

var textInput by remember { mutableStateOf("")}
        TextField(value = textInput, onValueChange = {textInput = it},
        label = { Text("Password")},
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            visualTransformation = PasswordVisualTransformation()
        )

The complete example is given below.

package com.example.example
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Email
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import com.example.example.ui.theme.ExampleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    TextfieldExample()
                }
            }
        }
    }
}

@Composable
fun TextfieldExample() {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        var textInput by remember { mutableStateOf("")}
        TextField(value = textInput, onValueChange = {textInput = it},
        label = { Text("Password")},
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
            visualTransformation = PasswordVisualTransformation()
        )
    }
    }


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ExampleTheme {
        TextfieldExample()
    }
}

And following is the output.

I hope this tutorial will be helpful for you.

Mohammed Rashid

Keep Reading