Removing TextChangedListener then re-adding it

Jason picture Jason · Jul 18, 2011 · Viewed 8.1k times · Source

So I've been trying to implement the TextWatcher for Android and ran into a few problems with the TextChangedListener being called multiple times or going into an infinite loop as I want to convert the text in the EditText widget into a currency formatted string.

What I did to work around this was create my own custom TextWatcher and then in the afterTextChanged event did something like the following

public class CurrencyTextWatcher implements TextWatcher {
    private EditText et;

    public CurrencyTextWatcher(EditText editText) {
        et = editText;
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }        

    public void afterTextChanged(Editable s) {
        et.removeTextChangedListener(this);
        et.setText(myCurrencyString);
        et.addTextChangedListener(this);
    }
}

So my question is, is there a better way of doing this? I want to have the one EditText Widget to hold where the edits go and the resulting formatted string.

Also is there actually any other issues that comes about removing and then adding a TextChangedListener like this?

Thanks in advance

Answer

Jeroen Coupé picture Jeroen Coupé · Jul 18, 2011

Everytime you will update (by eg calling set text) your editText the afterTextChanged will be called, so I think you should refrain from calling setText every time you are in afterTextChanged and only call it when something is really changing.

sth like this

if ( !myCurrencyString.equals(et.getText()))
{
    et.setText(myCurrencyString);
}