AND4011002849 AND4011002849 - 3 months ago 59
Java Question

TextWatcher inside AlertDialog not working

I'm trying to implement a mask in the EditText, the EditText appears when the user clicks in a TextView field and a alertdialog pops up, that EditText is inside an AlertDialog, but somehow the
listener is not working. What am I missing here?

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

numero = (TextView) findViewById(R.id.edit_numero);

numero.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog("Text");
}
});
}


public void dialog(String titulo) {

AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);

dialog.setCancelable(true);

LayoutInflater factory = LayoutInflater.from(MainActivity.this);
View view = factory.inflate(R.layout.observacao, null);

EditText observacao = (EditText) view.findViewById(R.id.numero);
Mask.insert("###.###.###-##", observacao);

TextView obslabel = (TextView) view.findViewById(R.id.obslabel);

obslabel.setText(titulo);

dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {



}
});

dialog.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});

dialog.setView(view);

dialog.show();
}

public static 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) {
}
};
}
}

Answer

You have to use the TextWatcher you obtain by calling

Mask.insert("###.###.###-##", observacao);

with the EditText, so change that line to

observacao.addTextChangedListener(Mask.insert("###.###.###-##", observacao));
Comments