Android Fragments 我如何使弹出窗口关闭时,点击它的外部?

a6b3iqyw  于 2023-01-26  发布在  Android
关注(0)|答案(7)|浏览(187)

我尝试制作一个弹出窗口,将有文本字段和信息询问用户,但我想知道如何使它,使用户可以通过点击弹出窗口外的主要片段/活动是关闭它。

@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);
        }
    }
}
1qczuiv0

1qczuiv01#

使您的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);
r7knjye2

r7knjye22#

通常你会用对话框和OnCancelListener来完成这一点。如果你想要弹出窗口的灵活性,你可以通过将其设置在可触摸的外部,然后调用setTouchInterceptor来拦截触摸。记住,如果触摸在窗口内部,则返回false,这样它将沿着触摸链进入实际视图。

n7taea2i

n7taea2i3#

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

ghhkc1vu

ghhkc1vu4#

你试过setCanceledOnTouchOutside吗?

afdcj2ne

afdcj2ne5#

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

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

4smxwvx56#

让弹出窗口setTouchable为true,setTouchInterceptor和get返回false,然后您可以单击弹出窗口的外部来关闭它。

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

如果行不通,请告诉我,我会看看我错过了什么。
这个答案是类似加布Sechan的答案,我只是没有发现之前,我发布这个答案...

xmjla07d

xmjla07d7#

2023年更新:现在已更改为setCancelable
dialog.setCancelable(true);

相关问题