OnFocusChange not always working

做~自己de王妃 提交于 2019-12-08 19:15:57

问题


In one of my activities I have three EditTexts and an OK button. The OnFocusChangeListener is set to all three EditTexts. The listener should trigger every time the focus is lost.

Switching between EditTexts works perfectly. But if the user presses the OK button there's no focus change (losing the focus) triggered for the EditText the user focused before pressing the button.

What's wrong with my code?

private class MyOnFocusChangeListener implements OnFocusChangeListener {
    private EditText editText;

    public MyOnFocusChangeListener(final EditText editText) {
        super();

        this.editText = editText;
    }

    @Override
    public void onFocusChange(final View view, final boolean isFocused) {
        if (!isFocused) {
            if (editText == editText1) {
                // Do a calculation
            } else if (editText == editText2) {
                // Do another calculation
            } else if (editText == editText3) {
                // Do a different calculation
            }
        }
    }
}

@Override
public void onCreate(final Bundle bundle) {
    // ...
    editText1.setOnFocusChangeListener(new MyOnFocusChangeListener(editText1));
    editText2.setOnFocusChangeListener(new MyOnFocusChangeListener(editText2));
    editText3.setOnFocusChangeListener(new MyOnFocusChangeListener(editText3));
    // ...
}

回答1:


You could try to clear the focus when user click on OK or other button....

e.g.

 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() 
 {
     public void onClick(DialogInterface dialog, int whichButton) 
     {
          editText1.clearfocus();
          editText2.clearfocus();
          editText3.clearfocus();
          ....
     }
 }



回答2:


You might want to try using: addTextChangedListener(..) in this case.




回答3:


Sounds like you could be having issues with touch mode, from the android docs:

"The relationship between touch mode, selection, and focus means you must not rely on selection and/or focus to exist in your application."




回答4:


It works if you bind onFocusChangeListener to the view element you want to be observed

editText.onFocusChangeListener = this
editText.setOnClickListener(this)

by keyword this it means the ViewHolder class




回答5:


To expand on @dong221, and incorporating the comment made by @Harald, one way to clear the focus without having to keep track of the last selected EditText is to get a reference to the currentFocus from the window object. Something like this:

myDoneButton.setOnClickListener { v -> 
    // Assuming we are in an Activity, otherwise get a reference to the Activity first
    window.currentFocus?.clearFocus()
}


来源:https://stackoverflow.com/questions/9427506/onfocuschange-not-always-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!