0

I know I can use:

myPopup.showAtLocation(layout, Gravity.NO_GRAVITY, x, y);
// OR
myPopup.showAtLocation(layout, Gravity.TOP|Gravity.LEFT, x, y);

To open a PopupWindow that's drawn from [x, y] as the Top-Left of the PopupWindow, drawn towards to Bottom-Right.

What I want instead however, is to draw from [x, y] as the Top-Right of the PopupWindow, drawn towards the Bottom-Left.

Here is a picture to make it more clear (The dot is my [x, y] position and the rectangle is my PopupWindow. The first picture shows how it's normally done, and the second is what I want to achieve.): enter image description here

So how do I correctly calculate the x and y of the second picture's gray point's location, while knowing the black point's location? I know the y can stay the same, but the x should be changed to something like:

  • x minus PopupWindow-width

The problem is that the PopupWindow's width and height are both set to wrap_content, so I don't know the size until after I draw it.

Does this mean I have to draw it (but make it invisible at first), then calculate the new x with the PopupWindow's MeasuredWidth in it's ViewTreeObserver's OnGlobalLayoutListener (to know when it's done rendering and the MeasuredWidth is known), then apply this new x and then make it Visible? Or is there an easier way to just let it draw at the correct position?

PS: I've also changed Gravity.NO_GRAVITY to Gravity.TOP|Gravity.RIGHT, if the PopupWindow is out of the screen it will automatically place it at the border of the Right/Top side (whichever side it's out of the screen).

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135

1 Answers1

0

You could get the size of your popup window by overriding the onMeasure method of the popup window (note that you have to subclass a View in order to do this). After that, you can calculate the offset of the x and y coordinates. Hope this helps.

overbet13
  • 1,654
  • 1
  • 20
  • 36
  • Though I haven't used your answer myself, but will accept it nonetheless. The solution I did for myself (not an answer to my question though) is using `android:layout_width="match_parent"` on my PopupWindow and only use the y-position from the Top. If anyone else want what I've sketched in my question above, I think @goldenJackal's solution to override onMeasure of your own extended PopupWindow class probably is the best solution. (My suggestion of the ViewTreeObserver's OnGlobalLayoutListener was when I Measured more than five different Views. With only one I would indeed override onMeasure.) – Kevin Cruijssen Jul 25 '14 at 15:05