Skip to content

Instantly share code, notes, and snippets.

@oscarito9410
Created July 12, 2019 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oscarito9410/c228adf7b7e3bab27a6ca1e3df9d18b7 to your computer and use it in GitHub Desktop.
Save oscarito9410/c228adf7b7e3bab27a6ca1e3df9d18b7 to your computer and use it in GitHub Desktop.
public class MoneyEditText extends TextInputEditText {
public MoneyEditText(Context context) {
super(context);
}
public MoneyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
private TextWatcher mWatcher;
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//Nothing to implement
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
MoneyEditText.this.removeTextChangedListener(mWatcher);
moneyFormat(charSequence, MoneyEditText.this);
MoneyEditText.this.addTextChangedListener(mWatcher);
}
@Override
public void afterTextChanged(Editable editable) {
//Nothing to implement
}
};
this.addTextChangedListener(mWatcher);
this.setFilters(new InputFilter[]{new InputFilter.LengthFilter(19)});
this.clearFocus();
}
public static void moneyFormat(CharSequence s, TextInputEditText amount) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols(new Locale("es-MX"));
DecimalFormat dec = new DecimalFormat("###,###,###,##0.00", symbols);
if (!s.toString().matches("^\\d{0,9}\\.\\d{1,2}$")) {
String userInput = "" + s.toString().replaceAll("[^\\d]", "");
if (userInput.length() > 0 && !userInput.equalsIgnoreCase("00")) {
BigDecimal parsed = new BigDecimal(userInput).setScale(2, BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR);
amount.setText("$" + dec.format(parsed));
amount.setSelection(amount.getText().length());
} else
amount.setText("");
}
}
public Double getAmount() {
try {
if (TextUtils.isEmpty(getText().toString()))
return 0d;
String amount = getText().toString().trim().replace("$", "");
amount = amount.replace(",", "");
return Double.parseDouble(amount);
} catch (NumberFormatException e) {
Timber.e(e);
return 0d;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment