OnFocusChange does not always work

In one of my actions I have three buttons EditTextand OK. The value is OnFocusChangeListenerset to all three EditTexts. The listener should start every time the focus is lost.

Switching between EditTextworks fine. But if the user presses the OK button, pressing the button does not change focus (loss of focus), but the button EditTextfocuses on the user.

What is 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));
    // ...
}
+7
source share
5 answers

You can try to clear focus when the user clicks OK or another button ...

eg.

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

, , :

" , , / , ".

+1

, onFocusChangeListener ,

editText.onFocusChangeListener = this
editText.setOnClickListener(this)

this , ViewHolder

0

To extend @ dong221 and include the comment made by @Harald, one way to clear focus without having to track the last selected one EditTextis to get a link to currentFocusfrom the object window. Like that:

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

All Articles