Search code examples
androidpasswordsandroid-edittext

How do I use the TransformationMethod interface?


I want to create an EditText which accepts passwords. I want to hide the character as soon as it is typed. So I tried to implement the TransformationMethod interface.

I am new to this. I tried the following code:

EditText editText = (EditText) findViewById(R.id.editText);
editText.setTransformationMethod(new PasswordTransformationMethod());

private class PasswordTransformationMethod implements TransformationMethod {

    @Override
    public CharSequence getTransformation(CharSequence source, View view) {
        return "/";
    }

    @Override
    public void onFocusChanged(View view, CharSequence source, boolean focused, int direction, Rect previouslyFocusedRect) {
        source = getTransformation(source, view);
    }
}

However, it throws java.lang.IndexOutOfBoundsException.

I am missing something. Any help will be appreciated.


Solution

  • Here is an example implementation of the PasswordTransformationMethod class that I use to convert passwords into dots:

    public class MyPasswordTransformationMethod 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; 
            }
    
            public char charAt(int index) {
                return '.'; 
            }
    
            public int length() {
                return mSource.length(); 
            }
    
            public CharSequence subSequence(int start, int end) {
                return mSource.subSequence(start, end); // Return default
            }
        }
    };
    

    You add it to an EditText like this:

    passwordEditText = (EditText) findViewById(R.id.passwordEditText);
    passwordEditText.setTransformationMethod(new MyPasswordTransformationMethod());