Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use TransformationMethod in android

I want to create an EditText which accepts passwords. I want to hide the character as soon as it is typed. So, I used a TransformationMethod. I am new to this so, I tried the following code.

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


private class PasswordTransformationMethod extends Transformation 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,

01-03 10:22:35.750: E/AndroidRuntime(2102): java.lang.IndexOutOfBoundsException

I am missing something. Any help will be appreciated.

like image 411
krishna Avatar asked Jan 03 '13 10:01

krishna


1 Answers

The above method has lots of errors.

So, I am sharing the code that I use to convert passwords into dots.

Create a separate class in the same Java file like this,

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

The implementation goes like this,

passwordEditText = (EditText) findViewById(R.id.passwordEditText);
passwordEditText.setTransformationMethod(new MyPasswordTransformationMethod());
like image 115
krishna Avatar answered Oct 16 '22 03:10

krishna