Android Nougat PopupWindow showAsDropDown(...) Gravity not working

Jimson picture Jimson · Sep 24, 2016 · Viewed 12k times · Source

I have this code.

PopupWindow popUp = new PopupWindow();
popUp.setFocusable(true);
popUp.setOutsideTouchable(true);        
popUp.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
popUp.setHeight(600);

popUp.setContentView(anchorView);
popUp.showAsDropDown(anchorView);
popUp.update();

And its perfectly works on Android Version < Android Nougat. But in Android Nougat, the popup is being displayed at the top of the screen instead of relative to the anchor view.

Answer

Liang Steve picture Liang Steve · Sep 28, 2016

It seems a bug in android 7.0. But you can solve it with a compatible way.

PopupWindow popUp = new PopupWindow();
popUp.setFocusable(true);
popUp.setOutsideTouchable(true);        
popUp.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
popUp.setHeight(600);

popUp.setContentView(anchorView);
  if (android.os.Build.VERSION.SDK_INT >=24) {
     int[] a = new int[2]; //getLocationInWindow required array of size 2
     anchorView.getLocationInWindow(a);
     popUp.showAtLocation(((Activity) mContext).getWindow().getDecorView(), Gravity.NO_GRAVITY, 0 , a[1]+anchorView.getHeight());
    } else{
     popUp.showAsDropDown(anchorView);
}

popUp.update();

Google will fix this bug in the future build. And there is a final workaround. You need give the height when creating pop.

PopupWindow popup = new PopupWindow(contentView, with, height);

Init pop as above, and you can only use popUp.showAsDropDown(anchorView) show this popup. In this way, you can ignore the version of the Android API.