KEYCODE_BACK第一次按下时不起作用

时间:2018-05-10 13:42:26

标签: java android android-studio

我无法在Android上覆盖后退按钮按下。

问题是,除了第一次以外,一切都很完美。 当我第一次加载应用程序并按下后退按钮时,它会暂停应用程序,这不是我想要的。除此之外,它按预期工作。

我的代码:

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.");
        }
    }

有什么想法吗?

提前谢谢

1 个答案:

答案 0 :(得分:1)

使用以下代码完美地处理片段。

    //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;
        }
    });