以编程方式将 EditText 的输入类型从 PASSWORD 更改为 NORMAL &反之亦然 [英] Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

查看:15
本文介绍了以编程方式将 EditText 的输入类型从 PASSWORD 更改为 NORMAL &反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个 EditText,其默认输入类型默认设置为 android:inputType="textPassword".它的右侧有一个 CheckBox,当它被选中时,会将该 EditText 的输入类型更改为 NORMAL PLAIN TEXT.代码是

In my application, I have an EditText whose default input type is set to android:inputType="textPassword" by default. It has a CheckBox to its right, which is when checked, changes the input type of that EditText to NORMAL PLAIN TEXT. Code for that is

password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

我的问题是,当取消选中 CheckBox 时,它应该再次将输入类型设置为 PASSWORD.我已经使用了-

My problem is, when that CheckBox is unchecked it should again set the input type to PASSWORD. I've done it using-

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

但是,edittext 中的文本仍然可见.令人惊讶的是,当我改变方向时,它会自动将输入类型设置为 PASSWORD 并且里面的文本是项目符号(显示为密码).

But, the text inside that edittext is still visible. And for surprise, when I change the orientation, it automatically sets the input type to PASSWORD and the text inside is bulleted (shown like a password).

有什么方法可以做到这一点?

Any way to achieve this?

推荐答案

以编程方式向该 EditText 添加一个额外的属性,您就完成了:

Add an extra attribute to that EditText programmatically and you are done:

password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

对于数字密码(pin):

For numeric password (pin):

password.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

另外,请确保光标位于 EditText 中文本的末尾,因为当您更改输入类型时,光标将自动设置为起始点.所以我建议使用以下代码:

Also, make sure that the cursor is at the end of the text in the EditText because when you change the input type the cursor will be automatically set to the starting point. So I suggest using the following code:

et_password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
et_password.setSelection(et_password.getText().length());

使用数据绑定时,可以使用如下代码:

When using Data Binding, you can make use of the following code:

<data>
        <import type="android.text.InputType"/>
.
.
.
<EditText
android:inputType='@{someViewModel.isMasked ? 
(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) :
InputType.TYPE_CLASS_TEXT }'

如果使用 Kotlin:

If using Kotlin:

password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD

这篇关于以编程方式将 EditText 的输入类型从 PASSWORD 更改为 NORMAL &amp;反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆