Search code examples
javaandroidtextwatcher

set Editview watchers only when the input from user?


I have 2 fields: dollars and yen. When i change the dollars field i want to show the converted num in the yen field,and vice versa.

my problem is this:

If i have 2 fields with watchers like:

addTextChangedListener(new TextWatcher()...) 

and both doing things to each other the app crashes because when i do a small change on 1 num in the dollars the watcher on the dollars and the yen is working which cause the crash... my solution right now is bad, i remove the listener from the yen when i change the dollars (and when done put the listener back).

Is there any way to only watch for a change via input and not by the default TextWatcher? (if the field changes but not via input, don't do nothing)


Solution

  • You can still use TextWatcher#onTextChanged but add a hasFocus() check, so that you only modify the other field if this field has the focus (being updated by user).

        mDollarsText.addTextChangedListener(new TextWatcher() {
            ...
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mDollarsText.hasFocus()) {
                    // show amount in yen
                    if (s == null || s.length() == 0) {
                       mYenText.setText("0");
                    } else { 
                       mYenText.setText(convertDollarsToYen(mDollarsText.getText().toString());
                    }
                }
            }
            ...
        });
    
        mYenText.addTextChangedListener(new TextWatcher() {
            ...
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mYenText.hasFocus()) {
                    // show amount in dollars
                    if (s == null || s.length() == 0) {
                       mDollarsText.setText("0");
                    } else { 
                       mDollarsText.setText(convertYenToDollars(mYenText.getText().toString());
                    }
                }
            }
            ...
        });
    

    I'm assuming here that you already have a convenience method for converting dollars<->yen.