PasswordVisualTransformation 将输入键转换为星号

PasswordVisualTransformation converts enter key to asterisk

我正在使用 Jetpack compose 实现 PasswordInput 可组合项,它是由 Android 开发者网站提供的 literally one of the examples

@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. 如何修改才能不这样做?

我要回答我的问题了。它需要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)
    )
}

Source