我正在尝试在EditText中实现一个掩码,当用户在TextView字段中单击并弹出一个alertdialog时,EditText会出现,EditText在AlertDialog中,但不知何故, 听众不工作。我在这里缺少什么?
@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) {
}
};
}
}
答案 0 :(得分:1)
您必须使用通过调用
获得的TextWatcher
Mask.insert("###.###.###-##", observacao);
使用EditText
,因此请将该行更改为
observacao.addTextChangedListener(Mask.insert("###.###.###-##", observacao));