转自:http://www.cnblogs.com/woaixingxing/p/5563171.html
View view = mInflater.inflate(R.layout.layout_popupwindow, null);
PopUpwindowLayout popUpwindowLayout = (PopUpwindowLayout) view.findViewById(R.id.llayout_popupwindow);
popUpwindowLayout.initViews(mContext, titles, false);
final PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//测量view 注意这里,如果没有测量 ,下面的popupHeight高度为-2 ,因为LinearLayout.LayoutParams.WRAP_CONTENT这句自适应造成的
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int popupWidth = view.getMeasuredWidth(); // 获取测量后的宽度
int popupHeight = view.getMeasuredHeight(); //获取测量后的高度
int[] location = new int[2];
// 允许点击外部消失
popupWindow.setBackgroundDrawable(new BitmapDrawable());//注意这里如果不设置,下面的setOutsideTouchable(true);允许点击外部消失会失效
popupWindow.setOutsideTouchable(true); //设置外部点击关闭ppw窗口
popupWindow.setFocusable(true);
// 获得位置 这里的v是目标控件,就是你要放在这个v的上面还是下面
v.getLocationOnScreen(location);
popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style); //设置动画
//这里就可自定义在上方和下方了 ,这种方式是为了确定在某个位置,某个控件的左边,右边,上边,下边都可以
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1] - popupHeight);
//因为ppw提供了在某个控件下方的方法,所以有些时候需要直接定位在下方时并不用上面的这个方法
ppwfilter.showAsDropDown(v); // 以触发弹出窗的view为基准,出现在view的正下方,弹出的pop_view左上角正对view的左下角 偏移量默认为0,0
ppwfilter.showAsDropDown(v, xoff, yoff); // 有参数的话,就是一view的左下角进行偏移,xoff正的向左,负的向右. yoff没测,也应该是正的向下,负的向上
ppwfilter.showAsDropDown(parent, xoff, yoff, gravity) //parent:传你当前Layout的id; gravity:Gravity.BOTTOM(以屏幕左下角为参照)... 偏移量会以它为基准点 当x y为0,0是出现在底部居中
注意:在安卓7.0上请看下面要注意的地方
/**
* 在android7.0上,如果不主动约束PopuWindow的大小,比如,设置布局大小为 MATCH_PARENT,那么PopuWindow会变得尽可能大,以至于 view下方无空间完全显示PopuWindow,而且view又无法向上滚动,此时PopuWindow会主动上移位置,直到可以显示完全。
* 解决办法:主动约束PopuWindow的内容大小,重写showAsDropDown方法:
* @param anchor
*/
@Override
public void showAsDropDown(View anchor) {
if(Build.VERSION.SDK_INT >= 24){
Rect visibleFrame = new Rect();
anchor.getGlobalVisibleRect(visibleFrame);
int height = anchor.getResources().getDisplayMetrics().heightPixels - visibleFrame.bottom;
setHeight(height);
}
super.showAsDropDown(anchor);
}
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());
}
- if (Build.VERSION.SDK_INT < 24) {
- popupWindow.showAsDropDown(view);
- } else {
- int[] location = new int[2];
- view.getLocationOnScreen(location);
- int x = location[0];
- int y = location[1];
- popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, y + view.getHeight());
- }