按下选项菜单时关闭弹出窗口

时间:2012-08-14 06:22:14

标签: android popup android-menu

当我按下硬件菜单键时,我实现了一个弹出窗口。现在,当我再次按下菜单键时,我想要关闭弹出窗口。

我试过这个

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_MENU) {
        if (pw.isShowing()) {
            pw.dismiss();
        } else {
            openpopup();
        }
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

这是打开的弹出窗口方法

public void openpop() {
    View view1 = getCurrentFocus();
    showpopup(view1);
}

这是showpopup方法

public void showpopup(View view) {

    pw.setTouchable(true);
    pw.setFocusable(true);
    pw.setTouchInterceptor(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                pw.dismiss();

                return true;
            }

            return false;
        }
    });

    try {
        pw.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
        pw.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        pw.setOutsideTouchable(false);
        pw.setContentView(popupView);
        pw.showAsDropDown(view, 0, 0);
        popUpShowed = true;
    } catch (Exception e) {
        Log.e("SAMPLE", "Exception", e);
    }

}

但是当我按下菜单时弹出窗口没有被解雇。

可能是什么问题?我需要以某种方式完成这项工作。请帮帮我。

3 个答案:

答案 0 :(得分:1)

你为什么不这样做?

private boolean popUpShowed = false;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_MENU) {
        if (popUpShowed) {
            pw.dismiss();
            popUpShowed = false;
        } else if(!popUpShowed){
            openpopup();
            popUpShowed = true;
        }
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

并删除弹出窗口中的keyListener。

答案 1 :(得分:1)

试试这个:

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 

if (keyCode == KeyEvent.KEYCODE_MENU) { 
    if (pw.isShowing()) { 
        closePW(); 
    } else { 
        openpopup(); // <- I think you do this already here
    } 
    return true; 
} 

return super.onKeyDown(keyCode, event); 
} 
}

// Put this function in the class which open the popup
// like your function openpopup()
public void closePW(){
   pw.dismiss();
}

答案 2 :(得分:1)

显然,第二次按菜单键不会触发 找到here the solution
希望它有所帮助。

编辑:
检查并创建另一种方法。这应该这样做:

boolean open = false;
boolean itemSelected = false;

@Override
public boolean onMenuOpened(int featureId, Menu menu) {

    if(!open || itemSelected) {
        showPopup();
        open = true;
        itemSelected = false;
    }
    return false;
}

@Override
public void onPanelClosed(int featureId, Menu menu) {
    if (open && !itemSelected) {
        closePopup();
        open = false;
    }
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    itemSelected = true;
    return false;
}

适用于Android 4.0.3。显然onPrepareOptionsMenu在v3之后改变了功能。