EditText密码显示和隐藏

Posted by phantomVK on January 1, 2018

显示EditText内容为明文:

setTransformationMethod(HideReturnsTransformationMethod.getInstance());

显示EditText内容为密文:

setTransformationMethod(PasswordTransformationMethod.getInstance());

实现被点击图标的OnClickListener

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