首页 > 解决方案 > PasswordVisualTransformation 将输入键转换为星号

问题描述

我正在PasswordInput使用 Jetpack compose 实现可组合,这实际上是 Android 开发者网站提供的示例之一:

@Composable
fun PasswordInput() {
    var password by remember { mutableStateOf("admin") }

    TextField(
        value = password,
        onValueChange = { password = it },
        label = { Text(text = stringResource(id = R.string.prompt_password)) },
        modifier = Modifier
            .fillMaxWidth(),
        visualTransformation = PasswordVisualTransformation(),
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
    )
}

在这里,我将密码默认为“admin”,长度为五个字符。它显示五个星号。

哈哈

但是如果用户在那里按下回车键,密码字段就会变成六个字符。

更多哈哈

问题:

  1. 为什么这样做?
  2. 如何修改它以不这样做?

标签: kotlinandroid-jetpack-compose

解决方案


我要回答我的问题。它需要singleLine = true,文档没有提到。

固定代码:

@Composable
fun PasswordInput() {
    var password by rememberSaveable { mutableStateOf("") }

    TextField(
        value = password,
        onValueChange = { password = it },
        maxLines = 1,
        singleLine = true,
        label = { Text(text = stringResource(id = R.string.prompt_password)) },
        modifier = Modifier
            .fillMaxWidth(),
        visualTransformation = PasswordVisualTransformation(),
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
    )
}

资源


推荐阅读