Answer the question
In order to leave comments, you need to log in
Text transformation in EditText?
Trying to do text formatting while writing it in android.
For example phone number:
I enter in EditText: +79032285588
And I see: +7 (903) 227-55-88
I tried to solve the problem using TransformationMethod , which is used, for example, to enter passwords (each input character is changed to an asterisk)
public class PhoneNumberTransformationMethod implements TransformationMethod {
public static final String TAG = "PhoneNumberTransformationMethod";
@Override
public CharSequence getTransformation(CharSequence source, View view) {
// Такой странный код используется потому, что source — mutable.
if (source instanceof Spanned) {
Spanned spanned = (Spanned) source;
return new PhoneNumberCharSequence(source);
} else {
return PhoneUtils.formatPhoneNumber(source.toString());
}
}
@Override
public void onFocusChanged(View view, CharSequence charSequence, boolean b, int i, Rect rect) {
}
private static class PhoneNumberCharSequence implements CharSequence {
private HashMap<String, String> phoneNumbers = new HashMap<String, String>();
private CharSequence mSource;
public PhoneNumberCharSequence(CharSequence source) {
mSource = source;
}
private String getCurrent() {
String currentString = mSource.toString();
String result = phoneNumbers.get(currentString);
if (result == null) {
result = PhoneUtils.formatPhoneNumber(currentString);
phoneNumbers.put(currentString, result);
}
return result;
}
@Override
public int length() {
return getCurrent().length();
}
@Override
public char charAt(int i) {
return getCurrent().charAt(i);
}
@Override
public CharSequence subSequence(int start, int end) {
return new SpannedString(this).subSequence(start, end);
}
}
}
CharSequence
only one character is taken from the returned character, even if the telephone number formatter returned several. CharSequence
? Answer the question
In order to leave comments, you need to log in
Beret or ready watcher
EditText inputField = (EditText) findViewById(R.id.inputfield);
inputField.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question