Skip to content

Instantly share code, notes, and snippets.

@malvre
Last active August 29, 2015 14:05
Show Gist options
  • Save malvre/8508d2330f806cf32c93 to your computer and use it in GitHub Desktop.
Save malvre/8508d2330f806cf32c93 to your computer and use it in GitHub Desktop.
[Android] CurrencyTextWatcher
Usage:
txtValor.addTextChangedListener(new CurrencyTextWatcher(txtValor));
public class Currency {
public static String toString(double value) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance();
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setCurrencySymbol("");
formatter.setDecimalFormatSymbols(symbols);
return formatter.format(value);
}
public static String toString(String value) {
double parsed = Double.parseDouble(value);
return Currency.toString(parsed);
}
public static double toDouble(String strValue) {
String cleanString = strValue.replaceAll("[,.]", "");
return Double.parseDouble(cleanString)/100;
}
}
public class CurrencyTextWatcher implements TextWatcher {
private String current = "";
EditText editText;
public CurrencyTextWatcher(EditText editText) {
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
editText.removeTextChangedListener(this);
double parsed = Currency.toDouble(s.toString());
String formatted = Currency.toString(parsed);
current = formatted;
editText.setText(formatted);
editText.setSelection(formatted.length());
editText.addTextChangedListener(this);
}
}
@Override
public void afterTextChanged(Editable s) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment