可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am developing an application for Android and I am using a popup window when the user clicks a specific menu bar object(consisting of small images lined up horizontally) on the bottom of the screen.
On the click I want the popup window to be anchored to the top-left corner of the view that was clicked and be shown on top.
The only methods that seem to be relevant are showAsDropDown(View anchor, int xoff, int yoff) and showAtLocation(View parent, int gravity, int x, int y). The problem with showAsDropDown is that it is anchored to the bottom-left corner of the view.
Is there another way to implement this?
回答1:
popupWindow.showAtLocation(...)
actually shows the window absolutely positioned on the screen (not even the application). The anchor in that call is only used for its window token. The coordinates are offsets from the given gravity.
What you actually want to use is:
popupWindow.showAsDropDown(anchor, offsetX, offsetY, gravity);
This call is only available in API 19+, so in earlier versions you need to use:
popupWindow.showAsDropdown(anchor, offsetX, offsetY);
These calls show the popup window relative to the specified anchor view. Note that the default gravity (when calling without specified gravity) is Gravity.TOP|Gravity.START
so if you are explicitly using Gravity.LEFT
in various spots in your app you will have a bad time :)
回答2:
popupWindow.showAtLocation(anchor, Gravity.BOTTOM, 0, anchor.getHeight());
回答3:
The one you want to use is showAtLocation(...)
. You specify the anchor view (the one the user clicks), and position it relative to that via the gravity
parameter and offsets. Think of the gravity
parameter like the PopupWindow
is almost like a child view and the parent view is like a container layout.
You should be able to put Gravity.LEFT | Gravity.TOP
as the parameter.
回答4:
I have this code: PopupWindow below a specific view (Gravity End) for all sdk version.
// display the popup[![enter image description here][1]][1]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mPopupWindow.showAsDropDown(v, 0, 0, Gravity.END);
} else {
mPopupWindow.showAsDropDown(v, v.getWidth() - mPopupWindow.getWidth(), 0);
}
Here View v is ImageButton Calendar.
回答5:
You just needed to move the popupWindow by the height of its anchor using the yoff parameter in the showAsDropDown(View anchor, int xoff, int yoff) syntax.
popupWindow.showAsDropDown(anchor, 0, -anchor.getHeight()+popupView.getHeight);
Also, be aware that if the max height allowed to anchor does not allow for the transformation, the popup might not show up properly.
回答6:
you can display the popup always above the anchor by following
popupWindow.showAsDropDown(anchor, 0, -anchor.getHeight()-popupView.getHeight);
回答7:
popupwindow.showAsDropDown(anchor,0, -125);
this thing work for me