关闭

EditText 动态切换密码 更改为"*"

标签: android
235人阅读 评论(0) 收藏 举报


if (!b) {
	//系统的PasswordTransformationMethod方法是显示 "·"
	//	edittext.setTransformationMethod(PasswordTransformationMethod.getInstance());
	//自定义AsteriskPasswordTransformationMethod类,显示 "*"
	edittext.setTransformationMethod(new AsteriskPasswordTransformationMethod());
} else {
	edittext.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
edittext.postInvalidate();
 //切换后将EditText光标置于末尾
CharSequence charSequence = edittext.getText();
     if (charSequence instanceof Spannable) {
                Spannable spanText = (Spannable) charSequence;
                Selection.setSelection(spanText, charSequence.length());
            }

自定义的 AsteriskPasswordTransformationMethod 类

public class AsteriskPasswordTransformationMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
    return new PasswordCharSequence(source);
}

private class PasswordCharSequence implements CharSequence {
    private CharSequence mSource;
    public PasswordCharSequence(CharSequence source) {
        mSource = source; // Store char sequence
    }
    public char charAt(int index) {
        return '*'; // This is the important part
    }
    public int length() {
        return mSource.length(); // Return default
    }
    public CharSequence subSequence(int start, int end) {
        return mSource.subSequence(start, end); // Return default
    }
}
};


来自stackoverflow 网友的方法,很好用。

http://stackoverflow.com/questions/14051962/change-edittext-password-mask-character-to-asterisk

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12119次
    • 积分:246
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:1篇
    • 译文:0篇
    • 评论:6条
    最新评论