Android中PopupWindow位置的確定一般通過showAsDropDown函數來實現,該函數有兩個重載函數,分別定義如下:
- public void showAsDropDown(View anchor) {
- showAsDropDown(anchor, 0, 0);
- }
-
- public void showAsDropDown(View anchor, int xoff, int yoff) {
- if (isShowing() || mContentView == null) {
- return;
- }
-
- registerForScrollChanged(anchor, xoff, yoff);
-
- mIsShowing = true;
- mIsDropdown = true;
-
- WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken());
- preparePopup(p);
-
- updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff));
-
- if (mHeightMode < 0) p.height = mLastHeight = mHeightMode;
- if (mWidthMode < 0) p.width = mLastWidth = mWidthMode;
-
- p.windowAnimations = computeAnimationResource();
-
- invokePopup(p);
- }
也就是說,調用第一個函數時,x和y坐標偏移量默認是0,此時PopupWindow顯示的結果如下中圖所示。而要實現PopupWindow顯示在wenwen的正下方時,就需要程序員自己進行坐標偏移量的計算,下右圖所示,當點擊wenwen時,PopupWindow顯示在正下方,這正是我們所需要的,對稱是一種美啊。