Skip to content

Instantly share code, notes, and snippets.

@ilhamsuaib
Created September 5, 2017 04:43
Show Gist options
  • Save ilhamsuaib/3e32a04400640a44f038df0cec6e3d30 to your computer and use it in GitHub Desktop.
Save ilhamsuaib/3e32a04400640a44f038df0cec6e3d30 to your computer and use it in GitHub Desktop.
set currency editText android
public class CustomTextWatcher implements TextWatcher{
private EditText edt;
private String current = "";
public CustomTextWatcher(EditText edt) {
this.edt = edt;
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals(current)) {
edt.removeTextChangedListener(this);
Locale local = new Locale("id", "id");
String replaceable = String.format("[Rp,.\\s]",
NumberFormat.getCurrencyInstance().getCurrency()
.getSymbol(local));
String cleanString = s.toString().replaceAll(replaceable,
"");
double parsed;
try {
parsed = Double.parseDouble(cleanString);
} catch (NumberFormatException e) {
parsed = 0.00;
}
NumberFormat formatter = NumberFormat
.getCurrencyInstance(local);
formatter.setMaximumFractionDigits(0);
formatter.setParseIntegerOnly(true);
String formatted = formatter.format((parsed));
String replace = String.format("[Rp\\s]",
NumberFormat.getCurrencyInstance().getCurrency()
.getSymbol(local));
String clean = formatted.replaceAll(replace, "");
current = formatted;
edt.setText(clean);
edt.setSelection(clean.length());
edt.addTextChangedListener(this);
}
}
}
implementation :
exEdt.addTextChangedListener(new CustomTextWatcher(exEdt));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment