OnFocusChange not always working

2019-06-20 01:24发布

问题:

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