我尝试使用带有TextWatcher的EditText创建遮罩。这个掩码需要格式化一个电话号码,但问题是这个掩码我有两种情况。情况1掩码需要有13个数字(99)9999-9999
,情况2需要有14个数字(99)99999-9999
。我希望当我键入数字格式化时。
我怎么能这样做?
我正在尝试这个。
//Activity
private EditText etPhone;
etPhone = (EditText)findViewById(R.id.etPhone());
etPhone.addTextChangedListener(new TelefoneMask(etPhone));
//TextWatcher
public class TelefoneMask implements TextWatcher {
private String current;
private EditText phone;
private StringBuilder mask = new StringBuilder();
public TelefoneMask(EditText phone) {
this.phone = phone;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public synchronized void afterTextChanged(Editable s) {
// mask1 -> (99)9999-9999 13 digits
// mask2 -> (99)99999-9999 14 digits
Integer size = s.length();
if(size == 10){
mask.append(s.toString());
mask.insert(0, "(");
mask.insert(3, ")");
mask.insert(8, "-");
}else if(size > 10){
mask.setLength(0);
mask.append(s.toString());
mask.insert(0, "(");
mask.insert(3, ")");
mask.insert(9, "-");
}
current = mask.toString();
phone.setText(current);
phone.setSelection(mask.length());
}
}
答案 0 :(得分:11)
解决了问题
我做了
public abstract class EditTextTelefoneMask {
private static final String mask8 = "####-####";
private static final String mask9 = "#####-####";
private static final String mask10 = "(##) ####-####";
private static final String mask11 = "(##) #####-####";
public static String unmask(String s) {
return s.replaceAll("[^0-9]*", "");
}
public static TextWatcher insert(final EditText editText) {
return new TextWatcher() {
boolean isUpdating;
String old = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
String str = EditTextTelefoneMask.unmask(s.toString());
String mask;
String defaultMask = getDefaultMask(str);
switch (str.length()) {
case 11:
mask = mask11;
break;
case 10:
mask = mask10;
break;
case 9:
mask = mask9;
break;
default:
mask = defaultMask;
break;
}
String mascara = "";
if (isUpdating) {
old = str;
isUpdating = false;
return;
}
int i = 0;
for (char m : mask.toCharArray()) {
if ((m != '#' && str.length() > old.length()) || (m != '#' && str.length() < old.length() && str.length() != i)) {
mascara += m;
continue;
}
try {
mascara += str.charAt(i);
} catch (Exception e) {
break;
}
i++;
}
isUpdating = true;
editText.setText(mascara);
editText.setSelection(mascara.length());
}
public void beforeTextChanged(CharSequence s, int start, int count,int after) {}
public void afterTextChanged(Editable s) {}
};
}
private static String getDefaultMask(String str) {
String defaultMask = mask8;
if (str.length() > 11){
defaultMask = mask11;
}
return defaultMask;
}
}
<强>活动强>
etPhone.addTextChangedListener(EditTextTelefoneMask.insert(etPhone));