Created
May 11, 2025 10:25
-
-
Save anta40/5456a0a2b11ee57de952de3784df0d3b to your computer and use it in GitHub Desktop.
Custom numeric on TextWatcher
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
/* | |
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