I have some intents inside a tab controller and for one of them I have an edit text which I need to know for sure when it has focus and when it loses this focus. I have mapped most of the events like focus listener, OnEditorActionListener and so on, now my only problem that remains is that when I have focus the soft keyboard appears and I want to close it either: 1) by the done button and not by the back button on the phone (disable back button to close keyboard while the keyboard is visible) 2) detect the back button event while the keyboard is visible so that I can pass the focus to some other control.
I have tried multiple ways, but with no success, like onBackPressed, onConfigurationChanged (add hiddenKeyboard in the manifest), key_down on activity and so on, but no success.
Does anybody succeded this? Practically I want when the keyboard is visible and I press back on phone, my edit text to lose focus (otherControl.requestFocus -> which is a relative layout).
In order to check when the 'BACK' button is pressed, use onBackPressed() method from the Android library. Next, perform a check to see if the 'BACK' button is pressed again within 2 seconds and will close the app if it is so.
you can use the keyboard_visibility package to achieve this.
Android provides no direct way to determine if the keyboard is open, so we have to get a little creative. The View class has a handy method called getWindowVisibleDisplayFrame from which we can retrieve a rectangle which contains the portion of the view visible to the user.
Old topic, but here is the expected answer
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
Toast.makeText(getContext(), "BACK", Toast.LENGTH_SHORT).show();
return true;
}
return super.onKeyPreIme(keyCode, event);
}
You should put this in a class that overrides EditText (class MyEditText extends EditText...)
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