Created
September 5, 2017 04:43
-
-
Save ilhamsuaib/3e32a04400640a44f038df0cec6e3d30 to your computer and use it in GitHub Desktop.
set currency editText android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
implementation : | |
exEdt.addTextChangedListener(new CustomTextWatcher(exEdt)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment