有没有一个聪明的方法让用户在隐藏和查看密码之间切换在一个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是编辑
推荐文章
- 视图绑定-我如何获得包含布局的绑定?
- 在Android Studio中改变矢量资产的填充颜色
- 在构建中编写注释的语法是什么?gradle文件?
- 如何以编程方式添加按钮色调
- 用Android Studio进行调试永远停留在“等待调试器”状态
- Openssl不被视为内部或外部命令
- 无法执行dex:在Eclipse中超过GC开销限制
- 如何以编程方式将视图添加到视图
- 单击url会打开默认浏览器
- 使用Retrofit刷新OAuth令牌,而不修改所有调用
- 多个dex文件定义了landoid /support/v4/accessibilityservice/AccessibilityServiceInfoCompat
- 如何获得动作栏的高度?
- 从活动外部调用startActivity() ?
- createScaledBitmap的过滤器参数做什么?
- 为什么我在使用adb时访问数据文件夹被拒绝?