Android: Two EditTexts dependent on each other

2019-07-24 18:54发布

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...

2条回答
唯我独甜
2楼-- · 2019-07-24 19:23

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.

查看更多
聊天终结者
3楼-- · 2019-07-24 19:41

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.

查看更多
登录 后发表回答