Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 583
Jimson Avatar asked Sep 24 '16 06:09

Jimson


1 Answers

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.

like image 98
Liang Steve Avatar answered Sep 20 '22 07:09

Liang Steve