I have an EditText that has an inputType of number. While the user is typing, I want to comma-separate the numbers. Here's a little illustration:
123 would be represented as 123
1234 would be represented as 1,234
12345 would be represented as 12,345
...and so on.
I tried adding a comma with TextWatcher as shown below:
EditText edittext = findViewById(R.id.cashGiven);
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.setText(separateWithComma(editText.getText().toString().trim()));
}
});
Pasting the separateWithComma()
method here would make this question extra lengthy but then, it works: I tested it on Eclipse. I think the addTextChangedListener does not work this way because my app freezes (and then crashes much later) when I do this.
Is there a better way to achieve this? Thanks in anticipation for a positive response.
Try to use
String.format
instead of what you have now.Replace this:
with this:
Another thing - your app may be getting this crash because every time that you are calling
setText()
insideafterTextChanged
, anotherafterTextChanged
is called and basically will create an infinite loop. If that is your problem you can find a good solution in here.I've gotten two good answers but I just wanted to add this:
The reason I was facing this problem was because
editText.setText(...)
was being called recursively inside theafterTextChanged()
function of my TextWatcher. As the previous answerers rightly stated, the solution is to temporarily stop theafterTextChanged()
method from firing this way:This way, we have carefully meandered our way. But this poses a NEW PROBLEM:
Using this strategy, we assume that the string within the EditText can easily be translated into an
int
. As we input more numbers, the app would definitely crash with a NumberFormatException because of the commas. Therefore, it is important we find a way to solve this problem. Here's a method I wrote to help me:Finally, we can do this:
I hope this helps someone out there. Merry coding!!
Try this code:
See this post
For those that might want to use this approach, change the return type of getCommalessNumber(String commaNumber) method to String instead of int.