OnBackPress is not called when a popup is displayed

I want to handle backpressure when a popup is displayed. To some extent, I want to reject it, and in some cases I do not want to perform any task in a popup.

When a popup is displayed, Activity onBackPress will not be called. Then, how can a popup be displayed when a popup is displayed?

+4
source share
4 answers

You need to call setBackgroundDrawable() on PopupWindow and set the background to not null . This sounds strange, but if background not configured for something on your PopupWindow , then it will not be able to detect events from Activity , such as a touch outside the window or a click on the back button.

I had the same problem just a few days ago. I will try to find the SO answer, where someone explains why this is so, but it may take me a bit. At the same time, try it, it should work.

Found

I did not have the opportunity to test it, but you can try to add keyEventListener and do something like this

 public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // put your code here } 

and add setOutsideTouchable(true) to your PopupWindow object and call update() on it. If this does not work, you may need to just leave the back button disabled when the popup appears and add your own Button to the window. I did not find anything else that allows you to select events with the button pressed.

+6
source

set the wallpaper this way

 popup.setBackgroundDrawable(new BitmapDrawable()); 

then install OnDismissListener like this

 popup.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { //do your code here } }); 
+4
source
 final PopupWindow popup = new PopupWindow(context); ... popup.setFocusable(false); //Setting this to true will prevent the events to reach activity below popup.setBackgroundDrawable(new BitmapDrawable()); //Or anything else, not null! 

Then in your activity:

 @Override public void onBackPressed() { //your code } 
+3
source

I know him too late, but he can help others. There are two ways to do this:

1) If the focus of the popup is not important to you, set

 mPopupInfoWindow.setFocusable(false); 

because if your popup is in focus, it will not return a press event for activity, therefore the onBackPressed () method is not called

2) If the focus window of the popup is configured for you, let it be true and set this listener in the popup. This code works for me

  mPopupInfoWindow.getContentView().setFocusableInTouchMode(true); mPopupInfoWindow.getContentView().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { mPopupInfoWindow.dismiss(); return true; } return false; } }); 
0
source

Source: https://habr.com/ru/post/1491438/


All Articles