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

password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

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

password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);

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

有办法实现吗?


当前回答

使用变换法:

隐藏:

editText.transformationMethod = PasswordTransformationMethod.getInstance()

可见:

editText.transformationMethod = SingleLineTransformationMethod.getInstance()

就是这样。

其他回答

引用

Final int[] count = {0};

    showandhide.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(count[0] ==0)
            {
                password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                count[0]++;
            }
            else {

                password.setInputType(InputType.TYPE_CLASS_TEXT |
                        InputType.TYPE_TEXT_VARIATION_PASSWORD);
                showandhide.setText("Hide");
                count[0]--;
            }

        }
    });
Checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // checkbox status is checked.
                if (isChecked) {
                        //password is visible
 PasswordField.setTransformationMethod(HideReturnsTransformationMethod.getInstance());     
                } else {
                        //password gets hided
             passwordField.setTransformationMethod(PasswordTransformationMethod.getInstance());       
                }
            }
        });

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

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

这招对我很管用:

mytext.setInputType(InputType.TYPE_CLASS_NUMBER);

只是对@Rajkiran提供的正确答案的补充评论,你可能想添加

etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

切换到正常输入状态,这样用户就不会被键盘的自动提示所困扰