Android: Two EditTexts dependent on each other

2019-07-24 19:12发布

问题:

I have two EditTexts. One is for example temperature in °C and the other is temperature in °F. When user edits one EditTexts I want the other to change accordingly.

Problem is that this changes make loop, where EditTexts make changes of each other. How to solve this? I would like to still have reaction in other EditText when I change the first one even programmatically, but without loop...

回答1:

Check if each EditText has focus first and only change it programmatically if it doesn't have focus.

http://developer.android.com/reference/android/view/View.html#hasFocus()

The one being edited by the user will have focus. The other one won't.



回答2:

Try

EditText et=new EditText(this);
final EditText et2=new EditText(this);
et1.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //DO CHANGE YOUR FAHRENHEIT HERE
et2.setText(....);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
});

EDIT: OnFocusChange of both EditText disable focus of the other.