Sunil Kumar
Sunil Kumar

Reputation: 7082

Manage the Phone Number inside the editText

I have doubt to manage the phone number in android. I want to looks like when user enter the number inside the EditText then formate entering looks like 999 999 9999 and after complete the entering thf format should be looks like (999) 999-9999. How can achieve this thing. I did my coding something but when user click on cross key of keyboad to back the text the it is not working perfect. Any help please!

Code:

@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
  String phone = edit_profilephone.getText().toString();
  if(phone.length() == 3)
  {
    edit_profilephone.setText(phone + " ");
    edit_profilephone.setSelection(4);
  }
  else if(phone.length() == 7)
  {
    edit_profilephone.setText(phone + " ");
    edit_profilephone.setSelection(8);
  }
  else if (phone.length() == 12)
  {
    int maxLength = 14;
    InputFilter[] fArray = new InputFilter[1];
    fArray[0] = new InputFilter.LengthFilter(maxLength);
    edit_profilephone.setFilters(fArray);

    StringBuilder buileString = new StringBuilder();
    String splitnumber[] = phone.split("\\s+");
    for (int i=0; i<splitnumber.length; i++)
    {
      if (i == 0)
      {
        buileString.append("(" + splitnumber[i] + ")");
      }
      else if (i == 1)
      {
        buileString.append(" " + splitnumber[i]);
      }
      else
      {
        buileString.append("-" + splitnumber[i]);
      }
    }
    edit_profilephone.setText(buileString.toString());
  }
}

Upvotes: 0

Views: 290

Answers (3)

Adrian Olar
Adrian Olar

Reputation: 2903

Also don't forget to put the text type in XML document for the edit text, it might help:) Good luck! Like this:

EditText
    android:id="@+id/editTextId"
    android:inputType="phone"
    android:digits="0123456789+" 
/> 

Upvotes: 0

Nikunj Patel
Nikunj Patel

Reputation: 22066

you can also go through with

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

For more Idea...

Upvotes: 1

user2340612
user2340612

Reputation: 10723

You can use PhoneNumberUtils.formatNumber() methods.

Or you can use a PhoneNumberFormattingTextWatcher. I've never used this before, but it seems to do all the work you want to do.

Upvotes: 1

Related Questions