简体   繁体   English

片段中的BackPressed无法正常运行

[英]BackPressed in Fragment not functioning properly

I have the following code: 我有以下代码:

v = inflater.inflate(R.layout.fragment_color, container, false);
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnKeyListener(new View.OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mMenu.isOpened()) {
                mMenu.closeMenu();
            } else {
            }
        }
        return false;
    }
});

When I press the back button, my menu closes like it should, but the app closes as well and it should not. 当我按下“后退”按钮时,我的菜单会像应有的那样关闭,但该应用程序也将关闭,而不应该关闭。

What am I doing wrong with what I have here? 我在这里有什么错? any help would be appreciated. 任何帮助,将不胜感激。

This is because finishing current activity is back key default behavior. 这是因为完成当前活动是后退键默认行为。 You need to override this behavior by returning true in your onKeyListner. 您需要通过在onKeyListner中返回true来覆盖此行为。 Below code should work for you. 下面的代码应该为您工作。

v = inflater.inflate(R.layout.fragment_color, container, false);
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnKeyListener(new View.OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mMenu.isOpened()) {
                mMenu.closeMenu();
               //It says that you have handled back key
                return true;
            } else {
            }
        }
        return false;
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM