fragment中弹出PopupWindow窗体,点击外界屏幕不消失问题解决

直接上代码

    private void loadPopupWindow(){
        Typeface iconfont = Typeface.createFromAsset(getActivity().getAssets(), "iconfont/iconfont.ttf");
        Typeface iconfont1 = Typeface.createFromAsset(getActivity().getAssets(), "iconfont1/iconfont.ttf");
        /* 每次加载这里会产生一堆临时对象,一个选择问题,是依靠GC回收临时对象还是尽量不依靠GC写永久对象? */
        if(popupWindow == null){
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_main, null);
            download = (LinearLayout) view.findViewById(R.id.capture);
            off = (LinearLayout) view.findViewById(R.id.cancel);
            capture = (TextView) view.findViewById(R.id.textView_download);
            capture.setTypeface(iconfont);
            cancel = (TextView) view.findViewById(R.id.textView_cancel);
            cancel.setTypeface(iconfont1);
            download.setOnClickListener(this);
            off.setOnClickListener(this);
            popupWindow = new PopupWindow(view);
            popupWindow.setWidth(360);
            popupWindow.setHeight(160);
            dismiss.setPopup(popupWindow);
        }
        int[] loc = new int[2];
        tool.getLocationOnScreen(loc);
        popupWindow.showAtLocation(tool, Gravity.NO_GRAVITY, loc[0]-110, loc[1] - popupWindow.getHeight());
    }

定位在碎片中某个view的上面显示,开始也是调用了setFocusable,setOutsideTouchable这两个方法,设为true可惜没用,猜测可能是碎片依附的活动失去了焦点。没办法,既然这样只能写一个屏幕点击事件(在主活动中),然后在写一个碎片的内部接口,主活动实现之,每次加载窗体的时候回调这个接口中的方法(为了把PopupWindow对象传给主活动)。
代码细节:

    /* 接口作用:点击popupwindow窗口外部使其消失,由由主活动实现,创建popupwindow对象时回调 */
    public interface PopupDismiss{
        void setPopup(PopupWindow window);
    }
/* 主活动里实现这个方法 */
public void setPopup(PopupWindow window){
        popupWindow = window;
    }
/* dismiss是接口对象 */
dismiss = (PopupDismiss) getActivity();
dismiss.setPopup(popupWindow);
/* 屏幕的点击事件,重写活动的这个方法就可以了 */
    public boolean onTouchEvent(MotionEvent event){
        if(popupWindow != null && popupWindow.isShowing()){
            popupWindow.dismiss();
        }
        return super.onTouchEvent(event);
    }

这样才解决问题,=。=

你可能感兴趣的:(android,Fragment,PopupWindo)