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


当前回答

一个很好的解决方案。设置一个按钮,然后使用下面的代码:

public void showPassword(View v)
{

    TextView showHideBtnText = (TextView) findViewById(R.id.textView1);

    if(showHideBtnText.getText().toString().equals("Show Password")){
        password.setTransformationMethod(null);
        showHideBtnText.setText("Hide");
    } else{
        password.setTransformationMethod(new PasswordTransformationMethod());
        showHideBtnText.setText("Show Password");
    }


}

其他回答

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

yourEditText.setTransformationMethod(new PasswordTransformationMethod());

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

android:password

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

yourEditText.setTransformationMethod(null);

试试这个:

首先定义一个全局标志,如下所示:

private boolean isShowPassword = false;

并设置监听器处理点击显示和隐藏密码按钮:

imgPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowPassword) {
                    etPassword.setTransformationMethod(new PasswordTransformationMethod());
                    imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_hide));
                    isShowPassword = false;
                }else{
                    etPassword.setTransformationMethod(null);
                    imgPassword.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_show));
                    isShowPassword = true;
                }
            }
        });

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

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

完整的示例代码将是

yourTextView.setTransformationMethod(new PasswordTransformationMethod());

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

yourTextView.setTransformationMethod(new DoNothingTransformation());

这是我的工作。这绝对对你有帮助

showpass.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(!isChecked){

                    // show password
                    password_login.setTransformationMethod(PasswordTransformationMethod.getInstance());

                    Log.i("checker", "true");
                }

                else{
                    Log.i("checker", "false");

                     // hide password
    password_login.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }

            }
        });

尝试https://github.com/maksim88/PasswordEditText项目在github。 你甚至不需要改变你的Java代码使用它。只改变

EditText

标签

com.maksim88.passwordedittext.PasswordEditText

在XML文件中。