PopupWindow TouchInterceptor无法正常工作

时间:2013-03-22 12:20:32

标签: android popupwindow ontouchlistener

我正在尝试测试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);
}

弹出窗口正确显示,看起来Touch Interceptor似乎根本不起作用:我没有得到任何日志信息,当然如果按下它之外弹出窗口也没有消失。

我是否需要在弹出窗口或托管它的Activity中设置一些其他属性?

2 个答案:

答案 0 :(得分:6)

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

使用此代码希望这有用

答案 1 :(得分:2)

如果您想要执行某些操作,当它在窗口外单击并且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 ....
      }
  });