Luís Henriques
Luís Henriques

Reputation: 634

KEYCODE_BACK doesn't work when pressed for the very first time

I'm having trouble overriding the Back Button press on Android.

The thing is, everything works perfectly except for the very first time. When I load the app and press the back button for the first time, it pauses the app, which is NOT what I want. Other than that, it works as expected.

My code:

private void setupDeviceButtons(){ // this is ran at the very beginning (onViewCreated())
        // setting up a listener to close the menus when the back button is pressed
        View view = getView();

        Log.e(TAG, "This happens when I load the app" );

        if (view != null) {

            Log.e(TAG, "This also happens when I load the app");

            view.setOnKeyListener((v, keyCode, event) -> {
                if (keyCode == KeyEvent.KEYCODE_BACK) {

                    Log.e(TAG, "But this doesn't happen when I press the back button for the first time.");

                    // we filter all actions that are not key down
                    if (event.getAction() != KeyEvent.ACTION_DOWN)
                        return true;

                    ...

                }
                return false;
            });
        } else {
            Log.e(TAG, "ERROR on setupDeviceButtons(): Unable to set back button behaviour. View is null.");
        }
    }

Any thoughts?

Thank you in advance

Upvotes: 1

Views: 1775

Answers (1)

Maraj Hussain
Maraj Hussain

Reputation: 1596

Use the below code working perfectly in fragments.

    //on fragment back pressed
    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK  && event.getAction()== KeyEvent.ACTION_DOWN) {
               // do your code on back pressed
                return true;
            }
            return false;
        }
    });

Upvotes: 2

Related Questions