How to hide the letters of a password while typing

Implementation of TransformationMethod to hide the letters of a password while typing:

public class LoginActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // example of usage
    ((TextView) findViewById(R.id.password)).setTransformationMethod(new HiddenPassTransformationMethod());
}

private class HiddenPassTransformationMethod implements TransformationMethod {

    private char DOT = '\u2022';

    @Override
    public CharSequence getTransformation(final CharSequence charSequence, final View view) {
        return new PassCharSequence(charSequence);
    }

    @Override
    public void onFocusChanged(final View view, final CharSequence charSequence, final boolean b, final int i,
                               final Rect rect) {
        //nothing to do here
    }

    private class PassCharSequence implements CharSequence {

        private final CharSequence charSequence;

        public PassCharSequence(final CharSequence charSequence) {
            this.charSequence = charSequence;
        }

        @Override
        public char charAt(final int index) {
            return DOT;
        }

        @Override
        public int length() {
            return charSequence.length();
        }

        @Override
        public CharSequence subSequence(final int start, final int end) {
            return new PassCharSequence(charSequence.subSequence(start, end));
        }
    }
}
}

Don't set the default edit text property as password. Instead, you can use addTextChangedListener() which will get called as soon as the user enters a character. Maintain an activity level string say "mPass". In the TextWatcher(), onTextChanged method, append character to your mPass and replace the input character by *.

But you will have to be careful regarding this coz application will pass control to the TextWatcher() even after you have replaced the character by *. If not handled properly it will get called recursively causing the application to crash.

Tedious way, but it will work...

Tags:

Android