Automatically format phone number in EditText

穿精又带淫゛_ 提交于 2019-12-05 01:20:26

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.

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);
}

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!