Shadow
Shadow

Reputation: 4782

showAsDropDown Gravity parameter not working

I am trying to center horizontally a PopUpWindow on the anchored view, but the Gravity.CENTER parameter is being ignored.

This is the method I am using:

popupWindow.showAsDropDown(anchorView, 0, 0, Gravity.CENTER);

No matter what CENTER gravity value I enter (also TOP or BOTTOM don't work), the pop-up always displays at the same place: the anchor's top left corner, unless I use the START or END values.

The documentation and javaDoc does not list any restriction on the values that it accepts, so I assume that it also accepts any of the CENTER, TOP and BOTTOM values: https://developer.android.com/reference/android/widget/PopupWindow#showAsDropDown(android.view.View,%20int,%20int,%20int)

I also tested this with anchor views that are smaller, equal and larger than the pop-up window and the pop-up window is set to not fill the screen width, as intended.

It appears that this method does nothing different from the equivalent method that does not take the gravity parameter

popupWindow.showAsDropDown(anchorView, 0, 0);

Is this a bug or is this not how it is suppose to be used?

Upvotes: 4

Views: 2954

Answers (3)

Chen Jiling
Chen Jiling

Reputation: 527

What I'm doing is:

fun showPopupWindow(popupWindow : PopupWindow){
    popupWindow.width = 200
    popupWindow.height = ViewGroup.LayoutParams.WRAP_CONTENT
    popupWindow.showAsDropDown(anchor, -(popupWindow.width - anchor.width)/2, 0,  Gravity.CENTER)
}

Make sure popupWindow.width and anchor.width are not 0, -1 or -2

Upvotes: -1

Vansh Arora
Vansh Arora

Reputation: 421

This is a bit late, but if you want to center the pop up window with showAsDropDown(), you can do this:

target.post(() -> {
        popupWindow.showAsDropDown(anchor, (anchor.getWidth() / 2), yOffset, Gravity.CENTER);
    });

It is inside target.post() to ensure that the anchor is drawn when we call getWidth(), otherwise it returns 0.

Upvotes: 0

TWL
TWL

Reputation: 6664

For PopupWindow.showAsDropDown(), it seems that is working as intended, tracing through its source, you can eventually see that the gravity parameter is only meant for horizontal values.

Tracking the value of gravity from PopupWindow.showAsDropDown() to PopupWindow.findDropDownPosition(), we can already see the hint @param gravity horizontal gravity specifying popup alignment

Then a step deeper to Gravity.getAbsoluteGravity() also hints at the same thing @param gravity The gravity to convert to absolute (horizontal) values.

But I believe what you are looking to achieve is at Show a PopupWindow centralized, which uses PopupWindow.showAtLocation()

PopupWindow.showAtLocation(View parent, int gravity, int x, int y)

Upvotes: 4

Related Questions