添加状态变量,判断弹出框的状态,并初始化:
private boolean popupFirst = true;
// 按下menu键,就弹出 if (keyCode == KeyEvent.KEYCODE_MENU) { if (popupFirst) { initPopWindow(); } } return true;
popView.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { // TODO Auto-generated method stub if ((keyCode == KeyEvent.KEYCODE_MENU) && (popWind.isShowing())) { if (!popupFirst) { popWind.dismiss(); popupFirst = true; } else { popupFirst = false; } } else if ((keyCode == KeyEvent.KEYCODE_MENU) && !(popWind.isShowing())) { // 显示弹出框 popWind.showAtLocation(popView, Gravity.RIGHT | Gravity.TOP, 20, 20); } return false; } });
在onkeyListener()对menu注册监听,根据状态变量判断当前弹出框的状态,并作出弹出或者注销的动作。
对消失的状态添加监听:
popWind.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { // TODO Auto-generated method stub popupFirst = true; } });这样,在消失的时候,重置状态变量,下次点击的时候才能准确的弹出来。因为窗体的消失,有可能是按其他控件或者menu键消失掉的,显然按控件消失的话,状态变量是不会改变的。
整个活动:
public class TestPop extends Activity { private boolean popupFirst = true; private PopupWindow popWind; private View popView; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.acypop); button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub initPopWindow(); } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_MENU) { if (popupFirst) { initPopWindow(); } } return true; } public void initPopWindow() { popView = LayoutInflater.from(this).inflate(R.layout.line, null); popView.setFocusable(true); popView.setFocusableInTouchMode(true); popView.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { // TODO Auto-generated method stub if ((keyCode == KeyEvent.KEYCODE_MENU) && (popWind.isShowing())) { if (!popupFirst) { popWind.dismiss(); popupFirst = true; } else { popupFirst = false; } } else if ((keyCode == KeyEvent.KEYCODE_MENU) && !(popWind.isShowing())) { // 显示弹出框 popWind.showAtLocation(popView, Gravity.RIGHT | Gravity.TOP, 20, 20); } return false; } }); popWind = new PopupWindow(popView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); popWind.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { // TODO Auto-generated method stub popupFirst = true; } }); // 使其聚集,可以点击里面的组件 popWind.setFocusable(true); // 设置允许在外点击消失 popWind.setOutsideTouchable(true); // 点击back也能消失 popWind.setBackgroundDrawable(new BitmapDrawable()); popWind.showAtLocation(popView, Gravity.RIGHT | Gravity.TOP, 20, 20); } }
注意:
1.外层的view获取焦点才能使onkeyListenner()监听起效。
popView.setFocusable(true); popView.setFocusableInTouchMode(true);