有没有一个聪明的方法让用户在隐藏和查看密码之间切换在一个android EditText? 许多基于PC的应用程序都允许用户这样做。


当前回答

你试过setTransformationMethod吗?它继承自TextView,并希望TransformationMethod作为参数。

你可以在这里找到更多关于TransformationMethods的信息。

它还有一些很酷的功能,比如字符替换。

其他回答

使用下面的代码

    val hidePasswordMethod = PasswordTransformationMethod()
    showOrHidePasswordButton.setOnClickListener {
        passwordEditText.apply {
            transformationMethod =
                if (transformationMethod is PasswordTransformationMethod) 
                   null //shows password
               else 
                   hidePasswordMethod //hides password
        }
    }

并确保你把它添加到你的密码编辑文本在布局

    android:inputType="textPassword"

如果你想要一个简单的解决方案,你可以使用这个扩展的Android的EditText去这个链接了解更多信息:https://github.com/scottyab/showhidepasswordedittext

将此添加到build.gradle中: 实现“com.github.scottyab: showhidepasswordedittext: 0.8”

然后更改XML文件中的EditText。

来自:< EditText

: < com.scottyab.showhidepasswordedittext.ShowHidePasswordEditText

这是所有。

注意:在XML设计中无法看到它,请尝试在模拟器或物理设备中运行它。

要显示圆点而不是密码,请设置PasswordTransformationMethod:

yourEditText.setTransformationMethod(new PasswordTransformationMethod());

当然,您可以在XML布局中的edittext元素中默认设置此选项

android:password

要重新显示可读密码,只需传递null作为转换方法:

yourEditText.setTransformationMethod(null);

您可以动态地更改TextView的属性。如果你将XML属性android:password设置为真,视图将显示点,如果你设置为假,文本显示。

使用setTransformationMethod方法,您应该能够从代码中更改此属性。(免责声明:我没有测试过该方法在视图显示后是否仍然有效。如果你遇到问题,请给我留下评论,让我知道。)

完整的示例代码将是

yourTextView.setTransformationMethod(new PasswordTransformationMethod());

隐藏密码。要显示密码,您可以设置一个现有的转换方法,或者实现一个空的TransformationMethod,它对输入文本不做任何操作。

yourTextView.setTransformationMethod(new DoNothingTransformation());

我的Kotlin扩展。编写一次,随处使用

fun EditText.tooglePassWord() {
this.tag = !((this.tag ?: false) as Boolean)
this.inputType = if (this.tag as Boolean)
    InputType.TYPE_TEXT_VARIATION_PASSWORD
else
    (InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)

this.setSelection(this.length()) }

您可以将此方法保存在任何文件中,并在任何地方使用它 像这样使用它

ivShowPassword.click { etPassword.tooglePassWord() }

其中ivShowPassword是点击imageview(眼睛)和etPassword是编辑