Android 的输入框(EditText)设置密码可见/不可见切换的最简单方法

使用Java代码修改EditText的密码切换输入模式的时候,密码显示后,再修改为隐藏模式就不起作用了。下面这两行代码是错误示范↓

editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

靠上面两行代码来实现EditText不可行,错误示范完毕。


正确做法:

先上效果图,Demo代码在后面


1.判断输入框目前是否显示密码:

et_password.getInputType() == 128 //如果editText.getInputType() 的值为128则代表目前是明文显示密码,为129则是隐藏密码

2.设置输入框输入模式为隐藏密码/显示密码:

et_password.setInputType(129);//设置为隐藏密码
et_password.setInputType(128);//设置为显示密码

主要代码就以上这三行,一行查询当前模式,两行设置输入模式。


注:以上知识来源于的网友:https://blog.csdn.net/dawanganban/article/details/23374187#commentsedit博客底下两位网友的评论,非常感谢:





以下是我自己写的(上面效果图的Demo)代码,有一个按钮,按下切换密码输入框的显示模式:

xml布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
    android:layout_width="match_parent" android:layout_height="match_parent"
    tools:context="com.fucaijin.demo.MainActivity">

    <EditText
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="请输入密码" />

    <Button
        android:id="@+id/bt_change_mode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="密码不可见"/>

</LinearLayout>

java代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText et_password = (EditText) findViewById(R.id.et_password);
        final Button bt_change_mode = (Button) findViewById(R.id.bt_change_mode);
        bt_change_mode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(et_password.getInputType() == 128){//如果现在是显示密码模式
                    et_password.setInputType(129);//设置为隐藏密码
                    bt_change_mode.setText("密码不可见");
                }else {
                    et_password.setInputType(128);//设置为显示密码
                    bt_change_mode.setText("密码可见");
                }
                et_password.setSelection(et_password.getText().length());//设置光标的位置到末尾
            }
        });


The end!


猜你喜欢

转载自blog.csdn.net/fucaijin/article/details/80236736