Android EditText 自定义密码样式,密码转换为*等特殊字符

时间:2025-01-26 14:57:41
import ;
import ;
//设置密码转换
(new TransformationMethod() {
    @Override
    public CharSequence getTransformation(CharSequence source, View view) {
        return new PasswordCharSequence(source);
    }

    @Override
    public void onFocusChanged(View view, CharSequence sourceText, boolean focused, int direction, Rect previouslyFocusedRect) {

    }

});

 

/**
 * 将密码转换成*显示
 * */
private class PasswordCharSequence implements CharSequence {
    private CharSequence mSource;

    public PasswordCharSequence(CharSequence source) {
        mSource = source; // Store char sequence
    }

    public char charAt(int index) {
        //这里返回的char,就是密码的样式,注意,是char类型的
        return '*';
    }

    public int length() {
        return ();
    }

    public CharSequence subSequence(int start, int end) {
        return (start, end); // Return default
    }
}