EditText密码显示和隐藏

January 1, 2018

显示EditText内容为明文:

1
setTransformationMethod(HideReturnsTransformationMethod.getInstance());

显示EditText内容为密文:

1
setTransformationMethod(PasswordTransformationMethod.getInstance());

实现被点击图标的OnClickListener

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
icon.setOnClickListener {
    editText.apply {
        if (inputType == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
            inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD
            transformationMethod = PasswordTransformationMethod.getInstance()
            icon.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, R.drawable.ic_eyes_closed))
            setSelection(text.length)
        } else {
            inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
            transformationMethod = HideReturnsTransformationMethod.getInstance()
            icon.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, R.drawable.ic_eyes))
            setSelection(text.length)
        }
    }
}