如何在外部单击时关闭弹出窗口?

时间:2018-03-26 03:24:01

标签: android android-layout android-fragments android-popupwindow

我正在尝试制作一个弹出窗口,其中包含文本字段和信息以询问用户,但我想知道如何制作它以便用户可以通过单击主要片段/活动的弹出窗口外部来关闭它是

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.tabstudygroups, container, false);

        listview = (ListView) rootView.findViewById(R.id.clist2);
        addCourseButton = (Button) rootView.findViewById(R.id.caddcoursebutton);

        // do stuff here

        addCourseButton.setOnClickListener(this);

        return rootView;
    }

    @Override
    public void onClick(View v) {
        if(v == addCourseButton) {
            View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_layout, null);
            final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);

            // HERE IS WHAT I THOUGHT WOULD MAKE IT BE ABLE TO ENABLE THE OUTSIDE TOUCH
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            popupWindow.setOutsideTouchable(true);

            Button btn = (Button) popupView.findViewById(R.id.button);

            popupWindow.showAsDropDown(popupView, 0, 0);
        }
    }
}

6 个答案:

答案 0 :(得分:1)

通常,您可以使用对话框和OnCancelListener执行此操作。如果你想要一个弹出窗口的灵活性,你可以通过将其设置在可触摸的外部来获得相同的东西,然后调用setTouchInterceptor来拦截触摸。如果触摸在窗口内,请记住返回false,因此它将沿着触摸链向下移动到实际视图。

答案 1 :(得分:1)

让你的PopupWindow成为wrap_content并使其可聚焦。

final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);

            // HERE IS WHAT I THOUGHT WOULD MAKE IT BE ABLE TO ENABLE THE OUTSIDE TOUCH
            popupWindow.setOutsideTouchable(true);
            popupWindow.setFocusable(true);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));


            Button btn = (Button) popupView.findViewById(R.id.button);

            popupWindow.showAsDropDown(popupView, 0, 0);

答案 2 :(得分:0)

您是否尝试过setCanceledOnTouchOutside

答案 3 :(得分:0)

当用户触摸弹出窗口外,您可以使用setCanceledOnTouchOutside(true)来关闭弹出窗口。

Dialog dialog = new Dialog(context)
dialog.setCanceledOnTouchOutside(true);

答案 4 :(得分:0)

让弹出窗口setTouchable为true,并设置setTouchInterceptor并返回false,然后你可以点击弹出窗口外面来关闭它。

popWindow.setTouchable(true);
popWindow.setTouchInterceptor(new View.OnTouchListener() {
    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }
});

如果它不起作用,请告诉我,我会看到我想念的。

这个答案类似于Gabe Sechan的答案,我在发布这个答案之前就没有发现......

答案 5 :(得分:0)

确保popupWindow.showAsDropDown(popupView, 0, 0); 在这些之后 popupWindow.setOutsideTouchable(true); popupWindow.setFocusable(true); popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

相关问题