Programmatically change input type of the EditText

2019-01-06 09:55发布

In my application, I have an EditText whose default input type is set to android:inputType="textPassword" by deault. 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);

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);

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

Any way to achieve this?

21条回答
The star\"
2楼-- · 2019-01-06 10:36

Use this code to change password to text and vice versa. This code perfectly worked for me. Try this..

EditText paswrd=(EditText)view.findViewById(R.id.paswrd);

CheckBox showpass=(CheckBox)view.findViewById(R.id.showpass);
showpass.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
    if(((CheckBox)v).isChecked()){
        paswrd.setInputType(InputType.TYPE_CLASS_TEXT);

    }else{
        paswrd.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
    }

}
});
查看更多
Anthone
3楼-- · 2019-01-06 10:38

For kotlin users:

password.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
查看更多
Summer. ? 凉城
4楼-- · 2019-01-06 10:39

Complete code when you want to apply the Password visibility in Password edit text.

Create a handle [ Any drawable or Checkbox]

on click or on Checked/Uncheck write this:

 if (edittext.getInputType() == (InputType.TYPE_CLASS_TEXT |
                    InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD )){

                edittext.setInputType(InputType.TYPE_CLASS_TEXT |
                        InputType.TYPE_TEXT_VARIATION_PASSWORD );
            }else{
                edittext.setInputType(InputType.TYPE_CLASS_TEXT |
                        InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );
            }

Do not forget to write this line:

 edittext.setSelection(edittext.getText().length());

It resets the cursor to the end of line.

查看更多
登录 后发表回答