2
I’m trying to automatically set a mask to the field, I don’t know any other way to do it, I’m doing it like this:
if(s.equals('(')){
edtCelular.setText(texto);
}else{
texto = "(" + telefone.substring(0, 2) + ") " + telefone.substring(2, 7) + "-" + telefone.substring(7, 11);
edtCelular.setText(texto);
}
And it’s not working, there’s some way to do this ?
It’s being set when the field’s phocus is leaving. According to the indication of an answer I made the update but it continues to give some differentiated problems.
I have the class MASK
that is like:
package com.fomedemais.FomeDemais;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class Mask {
public static String unmask(String s) {
return s.replaceAll("[.]", "").replaceAll("[-]", "")
.replaceAll("[/]", "").replaceAll("[(]", "")
.replaceAll("[)]", "");
}
public static TextWatcher insert(final String mask, final EditText ediTxt) {
return new TextWatcher() {
boolean isUpdating;
String old = "";
public void onTextChanged(CharSequence s, int start, int before,int count) {
String str = Mask.unmask(s.toString());
String mascara = "";
if (isUpdating) {
old = str;
isUpdating = false;
return;
}
int i = 0;
for (char m : mask.toCharArray()) {
if (m != '#' && str.length() > old.length()) {
mascara += m;
continue;
}
try {
mascara += str.charAt(i);
} catch (Exception e) {
break;
}
i++;
}
isUpdating = true;
ediTxt.setText(mascara);
ediTxt.setSelection(mascara.length());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
};
}
}
And when I do the event I’m doing so:
@FocusChange(R.id.edtTelefone)
void focusAlterado(View v, boolean hasFocus) {
if(!hasFocus){
edtTelefone.addTextChangedListener(Mask.insert("(##)####-####", edtTelefone));
}
}
LOG ERRORS
- WHEN I TYPE FOR THE FIRST TIME HE’S NOT AUTOMATICALLY TAKING THE MASK
- Depending on how I do it blocks the application and crashes, no error log appears. THIS HAPPENS WHEN I GO ON THE PHONE DIGITO, THEN CLICK ON THE PHONE DIGITO, DELETE CELL PHONE AND TYPE WHEN I WILL ERASE THE PHONE IT LOCKS
I made an edit on my reply with the class code
– Leonardo Dias
If you are not the author of this code you should reference where you copied it.
– ramaral
Just include one more #, staying that way "(##)#####-####"
– Leonardo Dias
@Leonardodias I’m having problems with your product, because it’s only working when I change the field
– Renan Rodrigues
Like the first time I type doesn’t catch the mask
– Renan Rodrigues
It has to work as you type in the phone numbers, that’s not it?
– Leonardo Dias
no, only when I edit
– Renan Rodrigues
I think this in this onTextChanged method is not working.
– Renan Rodrigues
Another thing, depending on how I do, the app hangs
– Renan Rodrigues
I took the acceptance of the question to make a review
– Renan Rodrigues