EditText+CheckBox displays the content of the input box in plaintext/ciphertext

Function: When CheckBox is selected, the content of the input box is displayed in plain text; when CheckBox is not selected, the content of the input box is displayed in cipher text.

Achieve in xml:

<EditText
        android:id="@+id/et"
        android:inputType="textPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <CheckBox
        android:id="@+id/cb"
        android:layout_below="@+id/et"
        android:text="显示密码"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Achieve in Java:

public class MainActivity extends AppCompatActivity {
    private EditText et;
    private CheckBox cb;

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

        et = (EditText) findViewById(R.id.et);
        cb = (CheckBox) findViewById(R.id.cb);

        //et.setCursorVisible(false);  进入页面时和输入时都不显示光标
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //et.setCursorVisible(false);  进入页面和第一次输入显示光标,之后的输入和改换显示方式之后不显示
                if (isChecked) {
                    //明文显示
                    et.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    //密文显示
                    et.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                //让输入的等待光标处于最后一个字符的后面而不是第一个字符的前面
                et.setSelection(et.getText().length());
            }
        });
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325484173&siteId=291194637