In one of my activities I have three EditText
s and an OK button. The OnFocusChangeListener
is set to all three EditText
s. The listener should trigger every time the focus is lost.
Switching between EditText
s 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));
// ...
}
You might want to try using: addTextChangedListener(..) in this case.
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();
....
}
}
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."
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With