Close Android Pop-up Window

Asked 2 years ago, Updated 2 years ago, 148 views

I wrote a code to display a pop-up window when you select an item in a list activity. The problem is that pressing the Back key does not close the pop-up window. I was asked to catch the back key in the activity, but it was not registered, so I tried to register it in the onkeylistener of the view I sent to the pop-up window as follows.

pop.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // // TODO Auto-generated method stub
            boolean res=false;
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                // // do something on back.
                Log.e("keydown","back");
                if (pw.isShowing()) {
                    Log.e("keydown","pw showing");
                    pw.dismiss();
                    res = true;
                }
            } } else {
                res = false;
            }
            return res;
        }
    });

This is communicated to the pop-up window as follows.

pw = new PopupWindow(
       pop, 
       240, 
       70, 
       true);

But it doesn't work either. Help me.

android popupwindow

2022-09-22 21:36

1 Answers

This problem occurs because the pop-up window does not respond to onTouch or onKey unless it has a non-null background. For help with this issue, see Code here. In general, you can force the issue to be resolved by invoking PopupWindow#setBackgroundDrawable(new BitmapDrawable(). In this case, you do not need to create an onKeyListener separately. You can also call PopupWindow#setOutsideTouchable(true) to make the pop-up window turn off when the user clicks on the area outside the window.

Deepened answer:

The reason why the background should not be null is because of what happens in PopupWindow#preparePopup. If background!= null, it creates an instance of PopupViewContainer and calls setBackgroundDrawable to place the view in it. PopupViewContainer is basically FrameLayout that responds to touch events and KeyEvent.KEYCODE_BACK events. However, if the background is null, it does not respond to any events and uses the developer-generated view. To resolve this issue, instead of using PopupWindow, you can extend the top-level ViewGroup to work as the question asks.


2022-09-22 21:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.