Je suis novice dans Android et je veux faire un masque pour un EditText avec un nombre décimal avec 3 décimales (ex: 0.658), j'ai besoin d'un masque cet utilisateur n'a pas besoin d'écrire le ".", seulement les chiffres, comme un masque conventionnel pour la monnaie.EditText masque avec 3 décimales dans java [android]
Je suis en train de créer un TextWatcher basé à ceci:
public static TextWatcher currency(final EditText editText) {
return new TextWatcher() {
String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().equals(current)) {
editText.removeTextChangedListener(this);
String cleanString = s.toString();
if(count != 0) {
String substr = cleanString.substring(cleanString.length() - 2);
if (substr.contains(".") || substr.contains(",")) {
cleanString += "0";
}
}
cleanString = cleanString.replaceAll("[R$,.]", "");
double parsed = Double.parseDouble(cleanString);
Locale locale = new Locale("pt", "BR");
String formatted = NumberFormat.getCurrencyInstance(locale).format((parsed/100));
formatted = formatted.replaceAll("[R$]", "");
current = formatted;
editText.setText(formatted);
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
};
}
Mais sans succès.
Il existe une meilleure façon de faire cela?
Merci.