前段時(shí)間在使用PopupWindow時(shí),對(duì)PopupWindow的顯示位置有一些疑惑,今天整理整理。
首先看看PopupWindow顯示的效果:

可以從動(dòng)圖中看到PopupWindow分別出現(xiàn)在了按鈕的左側(cè)、按鈕中間和按鈕右對(duì)齊的位置。
使用showAsDropDown(View anchor, int xoff, int yoff)方法就可以滿足這三個(gè)位置的顯示需求。
Left PopupWindow
首先顯示在按鈕下方左側(cè)的PopupWindow很好理解,就是showAsDropDown()的默認(rèn)顯示效果,直接調(diào)用showAsDropDown(button,0,0);就ok。
重點(diǎn)說(shuō)說(shuō)顯示在中間的PopupWindow和右對(duì)齊顯示的PopupWindow。
在說(shuō)之前先看一張圖:

在showAsDropDown()方法中,對(duì)應(yīng)的坐標(biāo)軸如上圖。原點(diǎn)在按鈕下方左側(cè),往右是X軸正方向,往下是Y軸正方向。
確定坐標(biāo)軸后,就可以計(jì)算B和C位置的PopupWindow的偏移量了。為了圖看起來(lái)更清晰,所以我把3個(gè)PopupWindow在Y軸上被畫(huà)成了三級(jí),實(shí)際上在Y軸是沒(méi)有偏移的。
Middle PopupWindow
從圖中可以計(jì)算出B位置在X軸的偏移量就是按鈕寬度的一半再減去popupwindow寬度的一半。
代碼如下:
mPopupWindow1.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); //這句代碼必須要才能獲得正確的popupwindow的寬度
int xOff;
int buttonWidth = button3.getWidth();
int popupwindowWidth = mPopupWindow1.getContentView().getMeasuredWidth();
xOff = buttonWidth / 2 - popupwindowWidth / 2;
mPopupWindow1.showAsDropDown(button3, xOff, 0);
不使用mPopupWindow1.getWidth()方法的原因是mPopupWindow1.getWidth()獲得的值是-2,因?yàn)槲以诓季治募性O(shè)置PopupWindow的寬度是wrap_content,不能獲取到正確的PopupWindow寬度,所以需要在手動(dòng)使用measure()方法測(cè)量PopupWindow的寬高后,再使用getMeasuredWidth()方法來(lái)獲取其寬度。
Right PopupWindow
Right PopupWindow也同理,從圖中可以看出right popupWindow在X軸的偏移量為按鈕寬度再減去PopupWindow的寬度。
代碼如下:
mPopupWindow1.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int xOff;
int buttonWidth = button4.getWidth();
int popupwindowWidth = mPopupWindow1.getContentView().getMeasuredWidth();
xOff = buttonWidth - popupwindowWidth;
mPopupWindow1.showAsDropDown(button4, xOff, 0);
底部的PopupWindow
底部的PopupWindow使用showAtLocation()顯示。
mPopupWindow2.showAtLocation(view, Gravity.BOTTOM, 0, 0);