Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing TextChangedListener then re-adding it

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

like image 560
Jason Avatar asked Jul 18 '11 06:07

Jason


2 Answers

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);
}
like image 119
Jeroen Coupé Avatar answered Oct 01 '22 09:10

Jeroen Coupé


How about following.

private void resetAddTagField() {
    if (edtView != null && textWatcherListener != null) {
        edtView.removeTextChangedListener(textWatcherListener);
        edtView.setText(DEFAULT_TEXT);    

        edtView.addTextChangedListener(textWatcherListener);
    }
}

What I learn: Do not underestimate power of TextWatcher :D :D

like image 45
nikhil2505 Avatar answered Oct 01 '22 09:10

nikhil2505