Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically format phone number in EditText

In my app, the user has to enter a phone number in an EditText field using the following format:

1(515)555-5555

I don't want the user to type "(", ")", or "-" while entering the number; I want these characters to be added automatically.

For example, suppose the user typed 1 -- the parenthesis after "1" should be added automatically, so that "1(" would be displayed. And I would like to have similar functionality while deleting.

I have tried to set text in the afterTextChanged method of onTextWatcher interface, but it is not working; instead it's causing an error. Any help will be greatly appreciated.

like image 660
Amit Kumar Avatar asked Feb 21 '11 10:02

Amit Kumar


2 Answers

you can try

editTextPhoneNumber.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

Check PhoneNumnerFormattingTextWatxher

in case you want your own implementation of TextWatcher then you can use folling appraoch:

import android.telephony.PhoneNumberFormattingTextWatcher;
import android.text.Editable;

/**
* Set this TextWatcher to EditText for Phone number
* formatting.
* 
* Along with this EditText should have
* 
* inputType= phone
* 
* maxLength=14    
*/
public class MyPhoneTextWatcher extends PhoneNumberFormattingTextWatcher {

private EditText editText;

/**
 * 
 * @param EditText
 *            to handle other events
 */
public MyPhoneTextWatcher(EditText editText) {
    // TODO Auto-generated constructor stub
    this.editText = editText;
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    // TODO Auto-generated method stub
    super.onTextChanged(s, start, before, count);

    //--- write your code here
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub
    super.beforeTextChanged(s, start, count, after);
}

@Override
public synchronized void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub
    super.afterTextChanged(s);
}

}
like image 55
Nayanesh Gupte Avatar answered Oct 15 '22 21:10

Nayanesh Gupte


You're probably running into a problem because afterTextChanged is re-entrant, i.e. changes made to the text cause the method to be called again.

If that's the problem, one way way around is to keep an instance variable flag:

public class MyTextWatcher implements TextWatcher {
    private boolean isInAfterTextChanged;

    public synchronized void afterTextChanged(Editable text) {
       if (!isInAfterTextChanged) {
           isInAfterTextChanged = true;

           // TODO format code goes here

           isInAfterTextChanged = false;
       }
    }
}

As an alternative, you could just use PhoneNumberFormattingTextWatcher -- it doesn't do the formatting that you described, but then again you don't have to do much to use it.

like image 27
Mike Avatar answered Oct 15 '22 23:10

Mike