Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phone number formatting an EditText in Android

Tags:

android

I am making a simple Address Book app (targeting 4.2) that takes name, address, city, state, zip and phone.

I want to format the phone number input as a phone number (XXX) XXX-XXXX, but I need to pull the value out as a string so I can store it in my database when I save. How can i do this?? I have the EditText set for "phone number" input but that obviously doesn't do too much.

like image 451
BackDoorNoBaby Avatar asked Mar 26 '13 21:03

BackDoorNoBaby


2 Answers

Simply use the PhoneNumberFormattingTextWatcher, just call:

editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher()); 

Addition
To be clear, PhoneNumberFormattingTextWatcher's backbone is the PhoneNumberUtils class. The difference is the TextWatcher maintains the EditText while you must call PhoneNumberUtils.formatNumber() every time you change its contents.

like image 118
Sam Avatar answered Sep 23 '22 04:09

Sam


There is a library called PhoneNumberUtils that can help you to cope with phone number conversions and comparisons. For instance, use ...

EditText text = (EditText) findViewById(R.id.editTextId); PhoneNumberUtils.formatNumber(text.getText().toString()) 

... to format your number in a standard format.

PhoneNumberUtils.compare(String a, String b); 

... helps with fuzzy comparisons. There are lots more. Check out http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html for more.

p.s. setting the the EditText to phone is already a good choice; eventually it might be helpful to add digits e.g. in your layout it looks as ...

<EditText     android:id="@+id/editTextId"     android:inputType="phone"     android:digits="0123456789+"  />  
like image 45
Trinimon Avatar answered Sep 24 '22 04:09

Trinimon