In my application, I have a editText which will accept phone number from the user, My target is, as soon as user enters the phone number it should be formatted (Like by appl
Supposing that you wanna format the phone number as per US format.
+1 (###) ###-####,1 (###) ###-####,###-####,###-###-####,011 $
The following will serve your purpose:
phoneEditText.addTextChangedListener(new TextWatcher() {
private boolean mFormatting; // a flag that prevents stack overflows.
private int mAfter;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
//called before the text is changed...
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mAfter = after; // flag to detect backspace.
}
@Override
public void afterTextChanged(Editable s) {
// Make sure to ignore calls to afterTextChanged caused by the work done below
if (!mFormatting) {
mFormatting = true;
// using US formatting.
if(mAfter != 0) // in case back space ain't clicked.
PhoneNumberUtils.formatNumber(
s,PhoneNumberUtils.getFormatTypeForLocale(Locale.US));
mFormatting = false;
}
}
});
If you need location specific services, i.e. for each location, you need specific format of that place (refer to this link). If you need only the format you needed, then write a custom function in the place of line in the above code snippet.
PhoneNumberUtils.formatNumber(
s, PhoneNumberUtils.getFormatTypeForLocale(Locale.US));