how to use TransformationMethod in android

2019-03-26 14:21发布

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.

1条回答
我只想做你的唯一
2楼-- · 2019-03-26 15:09

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());
查看更多
登录 后发表回答