2016-06-20 142 views
0

我有一个带有PopupWindow的片段。我用以下代码启动Popup:当外部点击时关闭PopupWindow在

private PopupWindow createPopup; 

    private void initiateWindow(){ 
     try { 
      LayoutInflater inflater = (LayoutInflater) getActivity() 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      View layout = inflater.inflate(R.layout.window_popup, 
        (ViewGroup) v.findViewById(R.id.popup_element)); 
      DisplayMetrics displaymetrics = new DisplayMetrics(); 
      getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); 
      int height = displaymetrics.heightPixels; 
      int width = displaymetrics.widthPixels; 


      createPopup = new PopupWindow(layout, width/2 + width/4, height/3, true); 
      createPopup.showAtLocation(layout, Gravity.CENTER, 0, 0); 


} catch (Exception e) { 
     e.printStackTrace(); 
     } 
     } 

它运行得很好。我想在外部点击时关闭窗口。这是一件很平常的事情,所以关于互联网上的话题有很多教程和问题。问题是 - 他们都无法工作。

我试过使用createPopup.setBackgroundDrawable(newColorDrawable(Color.TRANSPARENT)); createPopup.setOutsideTouchable(true); createPopup.setFocusable(true); 和类似answers

我还检查了是否可以使用此createPopup.setBackgroundDrawable(newColorDrawable(Color.BLACK));填充纯色弹出框后面的所有内容,以验证我是否有错误的核心代码,但它也没有帮助 - 与弹出布局无关的所有内容都保持可见状态。

+0

它会自动关闭时点击它之外。不是没有关闭? –

+0

不,它不。 –

+0

好的没问题什么弹出窗口包含什么视图textviews? –

回答

0

关闭弹出窗口时,在它之外的触摸 - 当失去专注

createPopup.setOutsideTouchable(true); 
createPopup.setFocusable(true); 

删除默认的黑色背景

createPopup.setBackgroundDrawable(new ShapeDrawable()); 

如果ShapeDrawable() didt工作中使用这一

createPopup.setBackgroundDrawable(new BitmapDrawable()); 

Same thread

+0

我已经试过这种方法。我试图添加黑色背景来检查它是否确实存在背景 - 这不是不幸的。 –

+0

see here http://stackoverflow.com/questions/12232724/popupwindow-dismiss-when-clicked-outside –

+0

我已经把它链接到我的问题 –

0

创建一个新的xml样式,如下所示。

<style name="AppTheme.PopupWindow"> 
    <item name="windowActionBar">false</item> 
    <item name="windowNoTitle">true</item> 
    <item name="android:windowIsFloating">true</item> 
    <item name="android:windowCloseOnTouchOutside">true</item> 
</style> 

创建主题后需要做的所有事情是将其应用于清单中的fragmentactivity。

<activity android:name=".PopupWindow" android:theme="@style/AppTheme.PopupWindow"></activity> 
+0

.java类是'Fragment'而不是'FragmentActivity'。它没有在清单中声明。 –