Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mask an EditText with Phone Number Format NaN like in PhoneNumberUtils

I want to make user inputted phone number in an editText to dynamically change format every time the user inputs a number. That is, when user inputs up to 4 digits, like 7144, the editText shows "714-4". I would like the editText to be dynamically updated to format ###-###-#### whenever the user inputs a digit. how can this be done? also, I am handling more than one editTexts.

like image 532
eunique0216 Avatar asked Nov 11 '10 09:11

eunique0216


Video Answer


2 Answers

Easiest way to do this is to use the built in Android PhoneNumberFormattingTextWatcher.

So basically you get your EditText in code and set your text watcher like this...

EditText inputField = (EditText) findViewById(R.id.inputfield); inputField.addTextChangedListener(new PhoneNumberFormattingTextWatcher()); 

Nice thing about using PhoneNumberFormattingTextWatcher is that it will format your number entry correctly based on your locale.

like image 155
brockoli Avatar answered Nov 13 '22 05:11

brockoli


Above answer is right but it works with country specific. if anyone want such formatted phone number(###-###-####). Then use this:

etPhoneNumber.addTextChangedListener(new TextWatcher() {                 @Override                 public void beforeTextChanged(CharSequence s, int start, int count, int after) {                     int digits = etPhoneNumber.getText().toString().length();                     if (digits > 1)                         lastChar = etPhoneNumber.getText().toString().substring(digits-1);                 }                  @Override                 public void onTextChanged(CharSequence s, int start, int before, int count) {                     int digits = etPhoneNumber.getText().toString().length();                     Log.d("LENGTH",""+digits);                     if (!lastChar.equals("-")) {                         if (digits == 3 || digits == 7) {                             etPhoneNumber.append("-");                         }                     }                 }                  @Override                 public void afterTextChanged(Editable s) {                  }             }); 

Declare String lastChar = " " in your activity.

Now add this line in xml of your edittext

android:inputType="phone" 

That's all.

Edited: If you want your edittext lenght to limit 10 digits add line below also:

android:maxLength="12" 

(It is 12 because "-" will take space two times)

like image 44
Rahul Sharma Avatar answered Nov 13 '22 03:11

Rahul Sharma