當點擊某個按鈕並彈出PopupWindow時,PopupWindow左下角默認與按鈕對齊,但是如果PopupWindow是下圖的那樣,會發 生錯位的情況,尤其是不同尺寸的平板上,那錯位錯的不是一般的不靠譜,而Android本身只提供瞭如下幾個方法設置PopupWindow顯示位置
- showAsDropDown(View anchor, int xoff, int yoff) 以anchor的左下角爲參照點,定義偏移
- showAsDropDown(android.view.View) 以anchor的左下角爲參照點,不偏移
- showAtLocation(View parent, int gravity, int x, int y) 以parent爲主容器,gravity爲對齊參照點,定義偏移
推薦用showAsDropDwon方法。
這裏是爲了讓PopupWindow居中顯示,所以需要自己定義橫向位移偏移量(其他位置類似)
int xoff = window.getWidth()/2-parent.getWidth()/2;
window.update();
window.showAsDropDown(parent, -xoff, 0);