在我的应用程序中,我有一个EditText,其默认输入类型设置为android:inputType="textPassword"默认。它的右侧有一个复选框,选中该复选框时,将该编辑文本的输入类型更改为普通纯文本。它的代码是

password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

我的问题是,当复选框未选中时,它应该再次设置输入类型为密码。我用过-

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

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

有办法实现吗?


当前回答

基于neeraj t和Everton Fernandes Rosario的回答,我写在Kotlin,其中密码是你的布局中的EditText的id。

// Show passwords' symbols.
private fun showPassword() {
    password.run {
        val cursorPosition = selectionStart
        transformationMethod = HideReturnsTransformationMethod.getInstance()
        setSelection(cursorPosition)
    }
}

// Show asterisks.
private fun hidePassword() {
    password.run {
        val cursorPosition = selectionStart
        transformationMethod = PasswordTransformationMethod.getInstance()
        setSelection(cursorPosition)
    }
}

其他回答

我改变了我的复选框的输入类型,所以在我的OnCheckedChangeListener我做:

passwordEdit.setInputType(InputType.TYPE_CLASS_TEXT| (isChecked? InputType.TYPE_TEXT_VARIATION_PASSWORD|~InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD));

最终成功了。

看起来像是TYPE_TEXT_VARIATION_VISIBLE_PASSWORD的布尔问题。反转标志,应该可以解决问题。

在你的情况下:

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|~InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

使用此代码将密码更改为文本,反之亦然

mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // checkbox status is changed from uncheck to checked.
                if (!isChecked) {
                        // hide password
                    mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                        // show password
                    mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });

完整的示例代码请参考http://www.codeproject.com/Tips/518641/Show-hide-password-in-a-edit-text-view-password-ty

使用变换法:

隐藏:

editText.transformationMethod = PasswordTransformationMethod.getInstance()

可见:

editText.transformationMethod = SingleLineTransformationMethod.getInstance()

就是这样。

这招对我很管用:

mytext.setInputType(InputType.TYPE_CLASS_NUMBER);

在寻找Visual Studio / Xamarin的类似解决方案时,我看到了这个帖子。下面是我使用Xamarin的方法。注意,这个实现在模式切换时保留type_text_flag_no_recommendations标志。

EditText et = FindViewById<EditText>(Resource.Id.ET);

显示字符: et.InputType = Android.Text.InputTypes.TextVariationVisiblePassword | android . text . inputtypes . textflagnosuggestion;

隐藏字符: et.InputType = Android.Text.InputTypes.TextVariationPassword | Android.Text.InputTypes.ClassText;

将位置设置为结束: int position = et.Text.Length; et.SetSelection(位置,位置);