6
I have an Edittext field, I want to know how I can define a mask for it to format the text inserted in the corresponding format, CPF or CNPJ, I tried using the method described in this other question but when the inserted text reaches 11 digits to define it as Cpf, all digits are exchanged for 1 with for example:
111.111.111-11
I searched but did not find where I went wrong, and it will be possible when the first three digits are entered, a . already be inserted?
My code:
public class CpfCnpjMaks {
private static final String cpfMask = "###.###.###-##";
private static final String cnpjMask = "##.###.###/####-##";
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 = "";
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String str = CpfCnpjMaks.unmask(s.toString());
String mask = "";
String defaultMaks = getDefaultMask(str);
switch (str.length()){
case 11:
mask = cpfMask;
break;
case 14:
mask = cnpjMask;
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;
}
isUpdating = true;
editText.setText(mascara);
editText.setSelection(mascara.length());
}
}
@Override
public void afterTextChanged(Editable s) {
}
};
}
private static String getDefaultMask(String str){
String defaultMaks = cpfMask;
if (str.length()>11){
defaultMaks = cnpjMask;
}
return defaultMaks;
}
}
More didactic for those who are starting: https://receitasdecodigo.com.br/android/como-inserir-mascara-em-um-edittext-no-android
– Renato Souza