PopupWindow的TouchInterceptor不起作用。

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);
}

弹出框显示正常,但是触摸拦截器似乎根本不起作用:我没有得到任何日志信息,当然如果在它外面按下,弹窗也不会消失。

在弹窗或承载它的活动中是否还有其他属性需要设置?


我曾经遇到过同样的问题,让我想想我是如何解决它的。 - a54studio
2个回答

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

使用这段代码,希望对您有所帮助。


嗨,我一直在处理一个代码片段,其中有一个弹出窗口内的列表。因此,我希望它可以被聚焦。如何处理任何外部触摸事件以关闭此弹出窗口?在我的下一个评论中,我将粘贴我的方法。 - Ankit Garg
popupWindow.setTouchInterceptor(new OnTouchListener() {@Override public boolean onTouch(View v, MotionEvent event) { popupWindow.dismiss(); if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { Log.e(TAG, "窗口外发生了某些事件:动作在外面"); return true; } Log.e(TAG, "窗口外发生了某些事件"); return false; } }); - Ankit Garg
你只需要删除你的代码并添加我的上面的代码,希望它能正常工作。 - Karthi
我尝试了您的代码并在此之后发布了我的问题。您的代码将弹出窗口的可聚焦状态设置为false,这会在触摸弹出窗口的外部或内部时关闭弹出窗口。然而,在我的场景中,有些项目是我想要选择(切换)的,因此我需要焦点。我该如何解决这个问题? - Ankit Garg
这对我来说很有用,在单击外部大小时隐藏密码。就像奇迹一样! - Phuong

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 ....
      }
  });

我尝试了你的解决方案,它运行良好。但是,一旦这个函数执行,如果我点击任何按钮,应用程序就会崩溃,显示错误java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 尝试找到解决方法,但没有成功。有什么建议吗? - Sabarish
当您尝试多次将视图添加到视图层次结构中时,就会发生这种情况。您应该查找addView()getLayoutInflater().inflate(R.layout.xyz, parentView, true) - skywall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接