EditText電話番号フォーマット
ネット上のいくつかの例を見て、自分で直して、白は噴き出さないでください.
/**
*
* @author Damon
* EditText
*/
public class PhoneNumberEditText extends EditText implements TextWatcher {
public PhoneNumberEditText(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public PhoneNumberEditText(Context context, AttributeSet attributeSet,
int defStyle) {
super(context, attributeSet, defStyle);
}
public PhoneNumberEditText(Context context) {
super(context);
setInputType(InputType.TYPE_CLASS_PHONE);
//setFilters(new InputFilter[] { new InputFilter.LengthFilter(13) });
addTextChangedListener(this);
}
@Override
public void afterTextChanged(Editable s) {
System.out.print(s);
}
public String getFormatString(String text) {
String result = "";
if (text.length() == 8) {
if (text.length() > 4) {
result = text.substring(0, 4) + " "
+ text.substring(4, text.length());
}
} else if (text.length() == 11) {
if (text.length() > 7) {
result = text.substring(0, 3) + " " + text.substring(3, 7)
+ " " + text.substring(7, text.length());
} else if (text.length() > 3) {
result = text.substring(0, 3) + " "
+ text.substring(3, text.length());
}
} else {
result = text;
}
return result;
}
boolean flag=false;
public String getPhoneNumber() {
CharSequence text = super.getText();
return text.toString().replaceAll(" ", "");
}
public String getOriginalNumber() {
return getText().toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int count, int after) {
String text = getPhoneNumber();
if (TextUtils.isEmpty(text)) {
return;
}
if (text.length()>13) {
text=(String) text.subSequence(0, 13);
}
flag=!flag;
if (flag) {
String result = getFormatString(text);
setText(result);
setSelection(result.length());
}
}
}