使用PopupWindow 遇到的坑
2017-06-11 本文已影响1722人
东之城
问题原因
PopupWindow 的height 使用 match_parent 或 fill_parent导致的问题
问题描述
api >=24(Android 7.0)时 View anchor 相对于anchor popupwindow 的位置 无效果 效果是全屏
public void showAsDropDown(View anchor)
public void showAsDropDown(View anchor, int xoff, int yoff)
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity)
public void showAtLocation(View parent, int gravity, int x, int y)
代码如下:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.showAsDropDown(button);
}
});
效果如下
![popupwindow_24.png](http:https://img.haomeiwen.com/i1000896/1a4b3aceadac9f27.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)解决方法(网上有很多方法)
if (Build.VERSION.SDK_INT < 24){
popupWindow.showAsDropDown(button);
} else { // 适配 android 7.0
int[] location = new int[2];
button.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
popupWindow.showAtLocation(button, Gravity.NO_GRAVITY, x,y+button.getHeight());
}
以上代码解决全屏问题
popupwindow-2.png
我擦 android 7.0 问题解决了,google android 7.1 出来了 MB 问题又来了
popupwindow_25.png
最后解决办法
if (Build.VERSION.SDK_INT < 24) {
popupWindow.showAsDropDown(button);
} else {
int[] location = new int[2]; // 获取控件在屏幕的位置
button.getLocationOnScreen(location);
if (Build.VERSION.SDK_INT == 25) {
int tempheight = popupWindow.getHeight();
if (tempheight == WindowManager.LayoutParams.MATCH_PARENT || screenHeight <= tempheight) {
popupWindow.setHeight(screenHeight - location[1] - button.getHeight());
}
}
popupWindow.showAtLocation(button, Gravity.NO_GRAVITY, location[0], location[1] + button.getHeight());
}
github
大家有什么解决办法???