Last active
June 20, 2023 05:55
-
-
Save stevdza-san/8f8d81935804fc5d32d924ac2e9b7cc6 to your computer and use it in GitHub Desktop.
Password Input Field - Jetpack Compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.compose.foundation.background | |
import androidx.compose.foundation.layout.Arrangement | |
import androidx.compose.foundation.layout.Column | |
import androidx.compose.foundation.layout.fillMaxSize | |
import androidx.compose.foundation.text.KeyboardOptions | |
import androidx.compose.material.Icon | |
import androidx.compose.material.IconButton | |
import androidx.compose.material.OutlinedTextField | |
import androidx.compose.material.Text | |
import androidx.compose.runtime.* | |
import androidx.compose.runtime.saveable.rememberSaveable | |
import androidx.compose.ui.Alignment | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.graphics.Color | |
import androidx.compose.ui.res.painterResource | |
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 | |
@Composable | |
fun PasswordTextField() { | |
Column( | |
modifier = Modifier | |
.fillMaxSize(), | |
horizontalAlignment = Alignment.CenterHorizontally, | |
verticalArrangement = Arrangement.Center | |
) { | |
var password by rememberSaveable { mutableStateOf("") } | |
var passwordVisibility by remember { mutableStateOf(false) } | |
val icon = if (passwordVisibility) | |
painterResource(id = R.drawable.design_ic_visibility) | |
else | |
painterResource(id = R.drawable.design_ic_visibility_off) | |
OutlinedTextField( | |
value = password, | |
onValueChange = { | |
password = it | |
}, | |
placeholder = { Text(text = "Password") }, | |
label = { Text(text = "Password") }, | |
trailingIcon = { | |
IconButton(onClick = { | |
passwordVisibility = !passwordVisibility | |
}) { | |
Icon( | |
painter = icon, | |
contentDescription = "Visibility Icon" | |
) | |
} | |
}, | |
keyboardOptions = KeyboardOptions( | |
keyboardType = KeyboardType.Password | |
), | |
visualTransformation = if (passwordVisibility) VisualTransformation.None | |
else PasswordVisualTransformation() | |
) | |
} | |
} | |
@Composable | |
@Preview | |
fun PasswordTextFieldPreview() { | |
Column( | |
modifier = Modifier | |
.fillMaxSize() | |
.background(Color.White), | |
horizontalAlignment = Alignment.CenterHorizontally, | |
verticalArrangement = Arrangement.Center | |
) { | |
PasswordTextField() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment