4

我正在尝试测试 PopupWindow 类。我创建了这个方法来显示弹出窗口:

    public void showPopup(){
            LayoutInflater layoutInflater   = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);  
            View popupView = layoutInflater.inflate(R.layout.popup, null);
            final PopupWindow popup = new PopupWindow(popupView, 
                       LayoutParams.WRAP_CONTENT,  
                         LayoutParams.WRAP_CONTENT);  
            popup.setOutsideTouchable(true);
            popup.setTouchable(true);
            popup.setTouchInterceptor(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    Log.d("POPUP", event.toString());
                    if(event.getAction() == MotionEvent.ACTION_OUTSIDE){
                        popup.dismiss();
                        return true;
                    }
                    return true;
                }
            });
            popup.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 200);
}

弹出窗口显示正确,顺便说一下,触摸拦截器似乎根本不起作用:我没有得到任何日志信息,当然,如果按下它,弹出窗口也不会消失。

我必须在弹出窗口或托管它的 Activity 中设置一些其他属性吗?

4

2 回答 2

6
 pw.setBackgroundDrawable (new BitmapDrawable());
 pw.setFocusable(false);
 pw.setOutsideTouchable(true); 

使用此代码希望这会有所帮助

于 2013-03-22T13:36:40.397 回答
4

如果你想做一些动作,当它在窗口外被点击并且两者都setFocusable()需要setOutsideTouchable()true 时,你可以考虑使用setOnDismissListener. onDismiss正如预期的那样,当对话框对话框被解除时,它的方法被调用:

  PopupWindow mPopupWindow = new PopupWindow(mRootView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
  mPopupWindow.setBackgroundDrawable(new ColorDrawable(android.R.color.transparent));
  mPopupWindow.setFocusable(true);
  mPopupWindow.setOutsideTouchable(true);
  mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
      @Override
      public void onDismiss() {
        // some action ....
      }
  });
于 2014-09-13T19:02:15.977 回答