Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect back event on android keyboard

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

like image 997
Catalin Avatar asked Jan 14 '12 09:01

Catalin


People also ask

How can I check back button is pressed in Android?

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.

How do you intercept the flutter back button when keyboard is shown?

you can use the keyboard_visibility package to achieve this.

How do I know if my Android keyboard is open?

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.


1 Answers

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

like image 84
Hrk Avatar answered Sep 20 '22 13:09

Hrk