In my application, I have a editText which will accept phone number from the user, My target is, as soon as user enters the phone number it should be formatted (Like by appl
This code works in both case delete and edit.
public class PhoneNumberFormattingTextWatcher implements TextWatcher {
EditText Edt;
int keyDel=0;
public PhoneNumberFormattingTextWatcher(EditText edt){
Edt =edt;
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
Edt.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL)
keyDel = 1;
return false;
}
});
if (keyDel == 0) {
int len = Edt.getText().length();
String input=Edt.getText().toString();
if(len == 4) {
Edt.setText( input.substring(0,3)+"-"+ input.substring(3) );
Edt.setSelection(Edt.getText().length());
}
if(len == 8) {
Edt.setText( input.substring(0,7)+"-"+ input.substring(7) );
Edt.setSelection(Edt.getText().length());
}
} else if(keyDel==1){
int len = Edt.getText().length();
if(len == 4||len==8) {
Edt.setText(Edt.getText().delete(Edt.getText().length()-1,Edt.getText().length()) );
Edt.setSelection(Edt.getText().length());
}
keyDel = 0;
}
}
@Override
public void afterTextChanged(Editable editable) {
}
}
You can use foolowing code it will work.
String number="5129892680";
String formattedNumber = PhoneNumberUtils.formatNumber(number);
Supposing that you wanna format the phone number as per US format.
+1 (###) ###-####,1 (###) ###-####,###-####,###-###-####,011 $
The following will serve your purpose:
phoneEditText.addTextChangedListener(new TextWatcher() {
private boolean mFormatting; // a flag that prevents stack overflows.
private int mAfter;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
//called before the text is changed...
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mAfter = after; // flag to detect backspace.
}
@Override
public void afterTextChanged(Editable s) {
// Make sure to ignore calls to afterTextChanged caused by the work done below
if (!mFormatting) {
mFormatting = true;
// using US formatting.
if(mAfter != 0) // in case back space ain't clicked.
PhoneNumberUtils.formatNumber(
s,PhoneNumberUtils.getFormatTypeForLocale(Locale.US));
mFormatting = false;
}
}
});
If you need location specific services, i.e. for each location, you need specific format of that place (refer to this link). If you need only the format you needed, then write a custom function in the place of line in the above code snippet.
PhoneNumberUtils.formatNumber(
s, PhoneNumberUtils.getFormatTypeForLocale(Locale.US));