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显示在相对于某个控件的某个位置
使用的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);



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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SunnyRivers

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值