Android Nougat PopupWindow showAsDropDown(...)Gravity无法正常工作

Jim*_*son 13 android popupwindow android-7.0-nougat

我有这个代码.

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();
Run Code Online (Sandbox Code Playgroud)

它完美适用于Android版<Android Nougat.但是在Android Nougat中,弹出窗口显示在屏幕顶部而不是相对于锚点视图.

小智 16

这似乎是android 7.0中的一个bug.但你可以用兼容的方式解决它.

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();
Run Code Online (Sandbox Code Playgroud)

谷歌将在未来的构建中修复此错误.还有最后的解决方法.你需要在创建pop时给出高度.

PopupWindow popup = new PopupWindow(contentView, with, height);
Run Code Online (Sandbox Code Playgroud)

如上弹出初始化,你只能使用popUp.showAsDropDown(anchorView)显示这个弹出窗口.通过这种方式,您可以忽略Android API的版本.


小智 6

7.0和7.1实现不同,所以要单独处理.

我在虚拟机(7.0和7.1)中测试过以下方法,没问题.

public void showFilterWindow(Context context, PopupWindow popupWindow,View showView, int xoff, int yoff) {
        if (Build.VERSION.SDK_INT < 24) {
            //7.0 The following system is used normally
            popupWindow.showAsDropDown(showView, xoff, yoff);
        } else {
            int[] location = new int[2];
            showView.getLocationOnScreen(location);
            int offsetY = location[1] + showView.getHeight() + yoff;
            if (Build.VERSION.SDK_INT == 25) {
                //?note!?Gets the screen height without the virtual key
                WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
                int screenHeight = wm.getDefaultDisplay().getHeight();
                /*
                 * PopupWindow height for match_parent,
                 * will occupy the entire screen, it needs to do special treatment in Android 7.1
                */
                popupWindow.setHeight(screenHeight - offsetY);
            }
            //Use showAtLocation to display pop-up windows
            popupWindow.showAtLocation(showView, Gravity.NO_GRAVITY, 0, offsetY);
        }
    }
Run Code Online (Sandbox Code Playgroud)