reiley
reiley

Reputation: 3761

How to dismiss PopupWindow when clicked outside?

In one of my activity, there is a button, which when clicked opens a PopupWindow. My intention is, when the PopupWindow is opened and user clicks anywhere on screen except the popup area, the PopupWindow should be dismissed.

For this I have set:

// onClick()
myPopupWindow.setOutsideTouchable(true);
myPopupWindow.setFocusable(false);

Issue is it works fine & PopupWindow gets dismissed when I click anywhere outside, but if I click on the button that generated this PopupWindow, then that event is consumed and PopupWindow first gets closed and then gets opened again.

I tried moving my button onclick() code to onTouch(). But if I return true, then button consumes every event & opens popup again and again, even with slightest drag while touching the screen. If I return false, it behaves same as in onClick() & opens the popup again when button is touches back.

So how can I dismiss the PopupWindow even when clicked on the button?

Upvotes: 1

Views: 1320

Answers (2)

V. Gerasimenko
V. Gerasimenko

Reputation: 229

I solved a similar problem as follows:

      settingsImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!settingsMenu.isShowing()) {
                settingsMenu.showAsDropDown(settingsImageButton);
                settingsImageButton.setEnabled(false);
            }
        }
    });
    settingsMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
                    return null;
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    settingsImageButton.setEnabled(true);
                }
            }.execute();
        }
    });

I call the method setEnabled() asynchronously, because onDismiss event is earlier than onClick event.

Upvotes: 0

luwionline
luwionline

Reputation: 186

Just disable that button after it has been clicked so that it can't be clicked when the pop-up window is displaying. button.setEnabled(false);

Upvotes: 2

Related Questions