pmb
pmb

Reputation: 2327

custom phone number formatting

In my Android application I want create my own phone number formatting but still couldn't find a way to do this.

I read about phone number libs and so on but still couldn't find a way to do this because all libs is working fine with US, German, French and other formats. I want to support Russian and these libs doesn't work fine.

The only way is I have to create my own formatting.

for example if I type

79123456789

it have to be formatted like in here

+7(912)345-67-89

I found libs for IOS (SHSPhoneTextField) but in Android I didn't.

Could anyone just tell me good solution in here?

  mPhoneNumber.addTextChangedListener(new PhoneNumberFormattingTextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                if (charSequence.length() == 11)
                mPhoneNumber.setText(PhoneNumberUtils.formatNumber(charSequence.toString()));
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

Upvotes: 0

Views: 1983

Answers (2)

alex
alex

Reputation: 5694

You shoul use PhoneNumberUtils with the desired Locale like this:

Locale localeRU = new Locale("ru","RU");
String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber, PhoneNumberUtils.getFormatTypeForLocale (localeRU));

Have a look for the appropriate Locale here.

@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
  if (charSequence.length() == 11)     
     Locale localeRU = new Locale("ru","RU");
     mPhoneNumber.setText(PhoneNumberUtils.formatNumber(charSequence.toString(), localeRU));
  }

Upvotes: 0

P Griep
P Griep

Reputation: 844

Maybe this will help (PhoneNumberUtils): http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html

A little example:

String formattedNumber = PhoneNumberUtils.formatNumber(unformattedNumber);

This will automatically format the number according to the rules for the country the number is from.

Look at PhoneNumberUtils for more options.

Upvotes: 1

Related Questions