PopupWindow - Dismiss when clicked outside

I have a PopupWindow on my activity, the thing is my PopupWindow still shows even when I'm interacting with my activity (say scrolling on my list). I can scroll through my list and the PopupWindow is still there.

What I want to achieve is when I'm touching/scrolling/clicking/etc on the screen which is not the PopupWindow, I want to dismiss the PopupWindow. Just like how a menu works. If you clicked outside of the menu, the menu will be dismissed.

I've tried setOutsideTouchable(true) but it won't dismiss the window. Thanks.


Solution 1:

Please try to set setBackgroundDrawable on PopupWindow that should close the window if you touch outside of it.

Solution 2:

I found that none of the answers supplied worked for me, except WareNinja's comment on the accepted answer, and Marcin S.'s will probably also work. Here's the part that works for me:

myPopupWindow.setBackgroundDrawable(new BitmapDrawable());
myPopupWindow.setOutsideTouchable(true);

Alternatively:

myPopupWindow.setFocusable(true);

Not sure what the differences are, but the ListPopupWindow source code actually uses the latter when it's modality is set to true with setModal, so at least the Android developers consider this a viable approach, and it's only one line.

Solution 3:

I met the same issues, and fixed it as below codes. It works fine for me.

    // Closes the popup window when touch outside.
    mPopupWindow.setOutsideTouchable(true);
    mPopupWindow.setFocusable(true);
    // Removes default background.
    mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

BTW, Don't use BitmapDrawable deprecated constructor, use this new ColorDrawable(android.R.color.transparent) to replace default background.

Have fun@.@