How to Show Popupwindow at Special Location

How to show PopupWindow at special location?

Locating an already displayed view is fairly easy - here's what I use in my code:

public static Rect locateView(View v)
{
int[] loc_int = new int[2];
if (v == null) return null;
try
{
v.getLocationOnScreen(loc_int);
} catch (NullPointerException npe)
{
//Happens when the view doesn't exist on screen anymore.
return null;
}
Rect location = new Rect();
location.left = loc_int[0];
location.top = loc_int[1];
location.right = location.left + v.getWidth();
location.bottom = location.top + v.getHeight();
return location;
}

You could then use code similar to what Ernesta suggested to stick the popup in the relevant location:

popup.showAtLocation(parent, Gravity.TOP|Gravity.LEFT, location.left, location.bottom);

This would show the popup directly under the original view - no guarantee that there would be enough room to display the view though.

Android - PopupWindow above a specific view

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 :)

Aligning popup window near the button clicked

I used popup.showAsDropDown(a_btn,0,0);

instead of
popup.showAtLocation(relative, Gravity.NO_GRAVITY, coordinateTop, 100);

and gave xoff and yoff.

a_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater lInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popup_view = lInflater.inflate(R.layout.popup_a, null);
final PopupWindow popup = new PopupWindow(popup_view,200,200,true);
popup.setFocusable(true);
popup.setBackgroundDrawable(new ColorDrawable());
popup.showAsDropDown(a_btn,0,0);

}
});


Related Topics



Leave a reply



Submit