thiago.adriano26
thiago.adriano26

Reputation: 1621

How can I format phone numbers using Xamarin for Android?

How can I format phone numbers using Xamarin for Android? I tried this code:

EditText inputField = (EditText) FindViewById(Resource.Id.editMensagemTelefone);
inputField.AddTextChangedListener(new PhoneNumberFormattingTextWatcher());

Upvotes: 2

Views: 1669

Answers (2)

m_drazzi
m_drazzi

Reputation: 126

Make sure you're using the Android.Telephony namespace when using the PhoneNumberFormattingTextWatcher()

See https://developer.xamarin.com/api/type/Android.Telephony.PhoneNumberUtils/

Upvotes: 4

Prashant
Prashant

Reputation: 138

Try this one:

_edtphonenumber=(EditText)findViewById(R.id.editText_phonenumber);

        _edtphonenumber.setTypeface(trajan_pro_regular);
        _edtphonenumber.addTextChangedListener(new TextWatcher() {
            private boolean mFormatting; // this is a flag which prevents the  stack overflow.
            private int mAfter;

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // nothing to do here.. 
            }

            //called before the text is changed...
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //nothing to do here...
                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;
                }
            }
        });

Upvotes: 1

Related Questions