Phone number format in android

android, android-edittext, phone-number

Solution

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

Problem

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 applying on text changed listener) , format is like `XXX-XXX-XXXX`. I wrote the code as ``` ePhone.addTextChangedListener(new TextWatcher() { private Pattern pattern; private Matcher matcher; String a; @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub boolean flag = true; if (flag) { if (((ePhone.getText().length() + 1) % 4) == 0) { if (ePhone.getText().toString().split("-").length <= 2) { ePhone.setText(ePhone.getText() + "-"); ePhone.setSelection(ePhone.getText().length()); } } a = ePhone.getText().toString(); } else { ePhone.setText(a); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stus } }); ``` But when the user wants to delete a number from this `editText`, its not working properly. Thanks in advance.

Original source