Skip to content

Instantly share code, notes, and snippets.

@anta40
Created May 11, 2025 10:25
Show Gist options
  • Save anta40/5456a0a2b11ee57de952de3784df0d3b to your computer and use it in GitHub Desktop.
Save anta40/5456a0a2b11ee57de952de3784df0d3b to your computer and use it in GitHub Desktop.
Custom numeric on TextWatcher
/*
Source: https://stackoverflow.com/questions/41734700/how-to-add-thousand-separator-in-android-edittext
*/
editText.addTextChangedListener(new TextWatcher() {
@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 editable) {
editText.removeTextChangedListener(this);
try {
StringBuilder originalString = new StringBuilder(editable.toString().replaceAll(",", ""));
int indx = 0;
for (int i = originalString.length(); i > 0; i--) {
if (indx % 3 == 0 && indx > 0)
originalString = originalString.insert(i, ",");
indx++;
}
editText.setText(originalString);
editText.setSelection(originalString.length());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
editText.addTextChangedListener(this);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment