Change gravity of PopupWindow
Asked Answered
D

2

5

I have a button that must show a popup window. And the popup window must be aligned with the right side of the button. That's how I do it.

button.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick( final View view ) {
        if(popup == null) {
            final View view = getLayoutInflater().inflate(R.layout.popup, null);
            popup = new PopupWindow(view);
        }

        if(popup.isShowing()) {
            popup.dismiss();
        } else {
            popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            popup.setFocusable(true);
            popup.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
            popup.showAsDropDown(button, 0, 0);
        }
    }
} );

This code works fine but the popup window is aligned with the left side of the button. Is there an easy way to change gravity of PopupWindow?

Dilapidation answered 29/11, 2010 at 12:6 Comment(0)
D
14

The easiest way I've found is to specify the x-offset parameter:

final View view = popup.getContentView();
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
popup.showAsDropDown(button, button.getWidth() - view.getMeasuredWidth(), 0);
Dilapidation answered 30/11, 2010 at 13:40 Comment(4)
I'd have trouble using that with ListPopupWindow though.Asperity
Where is getContentView()?!!Endorse
@Endorse That's a method of PopupWindowDilapidation
Okay I see.... I busted a gut trying to fix the popupMenu.. it's a literal nightmare! However, popuWindow needs massive amount of code and implementation. I ended up preventing the mobile phone rotation to avoid this confusion!Endorse
F
-5

You can try to change it from the xml file:

android:layout_graviry="left"
Foal answered 29/11, 2010 at 12:11 Comment(1)
PopupWindow is created as an other window, not a view, so this method doesn't work.Dilapidation

© 2022 - 2024 — McMap. All rights reserved.