Search code examples
androidandroid-layoutandroid-fragmentsandroid-popupwindow

How do I enable a popup to close when clicked outside of it?


I am trying to make a popup that is going to have text fields and information to ask the user but I am wondering how to make it so that the user can close it by clicking outside of the popup where the main fragment / activity is.

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

Solution

  • Make your PopupWindow to wrap_content and make it focusable.

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