Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnFocusChange not always working

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));
    // ...
}
like image 710
Harald Wilhelm Avatar asked Feb 24 '12 08:02

Harald Wilhelm


4 Answers

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

like image 28
AnnaM Avatar answered Nov 17 '22 00:11

AnnaM


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();
          ....
     }
 }
like image 105
dong221 Avatar answered Nov 17 '22 00:11

dong221


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

like image 1
Theblacknight Avatar answered Nov 17 '22 02:11

Theblacknight


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()
}
like image 1
Nicolás Carrasco-Stevenson Avatar answered Nov 17 '22 00:11

Nicolás Carrasco-Stevenson