PopupWindow正确使用方式

开发模板代码:


View view1 = LayoutInflater.from(this).inflate(R.layout.first_pop, null);
PopupWindow popupWindow = new PopupWindow(view1, LinearLayout.
        LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT);
popupWindow.setFocusable(true);
//默认显示在左下角
 popupWindow.showAsDropDown(btnShow);
PopupWindow正确使用方式


我们在开发中一般会有两种基本的操作,
第一种:让popupWindow显示在相对于某个控件的某个位置
使用的api :

showAsDropDown(View anchor, int xoff, int yoff)

使用要点:
通过计算x和y方向需要偏移的距离来调整popupWindow相对于指定控件的位置
计算要点:
分别计算出popupWindow和该控件的宽和高
(注意:为了确保popupWindow在使用时,系统已经进行了测量,我们需要手动触发,只需调用如下代码:
view1.measure(0, 0);
此时就可以计算宽和高:
int measuredWidth = btnShow.getMeasuredWidth();
int measuredHeight = btnShow.getMeasuredHeight();

int measuredWidth1 = view1.getMeasuredWidth();
int measuredHeight1 = view1.getMeasuredHeight();

int i = (measuredWidth - measuredWidth1) / 2;
int i1 = measuredHeight + measuredHeight1;


这里举几个常用的案例(显示在控件的正下方、正上方、正左方、正右方)
(1)显示在button的正下方:
popupWindow.showAsDropDown(btnShow, i, 0);
(2)显示在button的正上方:
popupWindow.showAsDropDown(btnShow, i, -i1);

(3)显示在button的正左方:
popupWindow.showAsDropDown(btnShow, -measuredWidth1, -i1 / 2);

(4)显示在button的正右方:
popupWindow.showAsDropDown(btnShow, measuredWidth, -i1 / 2);


第二种:让popupWindow显示在相对于当前界面(比如Activity)的某个位置
使用的api :
showAtLocation(View parent, int gravity, int x, int y)    (此处 parent 可以使该界面里的任意控件)

popupWindow.showAtLocation(btnShow, Gravity.BOTTOM, 0, 0);

PopupWindow正确使用方式


只需要调整Gravity和x、y即可,这样就可以让popupWindow显示在该界面的任何位置了,超级简单