I would like to know how to create a mask in an EditText in ABC-1234 format. I'm trying something like the example below, but with no success yet.
public abstract class PlacaVeiculoMask {
public static String PLACA_MASK = "???-####";
public static String unmask(String s) {
return s.replaceAll("[A-Z]{3}-[0-9]{4}", "");
}
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 = PlacaVeiculoMask.unmask(s.toString());
String mask = PLACA_MASK;
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) {
}
};
}
}