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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With