Android 7.0 or above (including 8.0), popupWindow pop-up position is abnormal, solution

Keywords: Android Mobile

Generally, in our App, click the position of the title to pop up the menu, and the effect is as follows:

Is that hard? Picking up the keyboard is doing

public void showAsDropDown(View anchor, int xoff, int yoff) {
    showAsDropDown(anchor, xoff, yoff, DEFAULT_ANCHORED_GRAVITY);
}
  • 1
  • 2
  • 3

But it's not always what we think. Up to now, Android 7.0, including (7.1, 8.0) system's mobile phone pop-up window, doesn't play cards according to the routine at all, so our same code has different effects

Hello! Where's my title bar??? Eaten by you???

Spit it out for me!!!

It's hard for me? Browser open > Baidu open > XXX can't display normally

Whiz...

You may see code like this

if (Build.VERSION.SDK_INT >= 24) {
     int[] location = new int[2];
     anchor.getLocationOnScreen(location);
     // 7.1 Version processing
     if (Build.VERSION.SDK_INT == 25) {
         WindowManager windowManager = (WindowManager) pw.getContentView().getContext().getSystemService(Context.WINDOW_SERVICE);
         if (windowManager != null) {
             int screenHeight = windowManager.getDefaultDisplay().getHeight();
             // PopupWindow height for match_parent, will occupy the entire screen, it needs to do special treatment in Android 7.1
             pw.setHeight(screenHeight - location[1] - anchor.getHeight() - yoff);
         }
     }
     pw.showAtLocation(anchor, Gravity.NO_GRAVITY, xoff, location[1] + anchor.getHeight() + yoff);

 } else {
     pw.showAsDropDown(anchor, xoff, yoff);
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Try the effect, it's OK

If you turn off the webpage when you come here, I can only say that bug is still waving to you? Do you want MM test to find you? Is it (evil...)

Android 8.0 system, this way can't solve

Ultimate solution (7.0, 7.1, 8.0)

/**
 *
 * @param pw     popupWindow
 * @param anchor v
 * @param xoff   x Axis deviation
 * @param yoff   y Axis deviation
 */
public static void showAsDropDown(final PopupWindow pw, final View anchor, final int xoff, final int yoff) {
    if (Build.VERSION.SDK_INT >= 24) {
        Rect visibleFrame = new Rect();
        anchor.getGlobalVisibleRect(visibleFrame);
        int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
        pw.setHeight(height);
        pw.showAsDropDown(anchor, xoff, yoff);
    } else {
        pw.showAsDropDown(anchor, xoff, yoff);
    }

} It has been tested. You can use int[] location = new int[2]; findViewById(R.id.layout_poi).getLocationOnScreen(location); int x = location[0]; int y = location[1]; showAsDropDown(cityPopup,findViewById(R.id.layout_poi),0,y+findViewById(R.id.layout_poi).getHeight()); Finish work!

Posted by hmb3801 on Tue, 31 Mar 2020 23:43:19 -0700