user2057762 user2057762 - 1 month ago 5
Android Question

Get The Measures of Popup Window

I already set up the pop up window, but i want to center it below the button (View v), that needs to be clicked to open it:

public void showPopup(Context c, View v){
int[] location = new int[2];
v.getLocationOnScreen(location);

ViewGroup base = (ViewGroup) getView().findViewById(R.id.pup_pattern);
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View pupLayout = inflater.inflate(R.layout.linearlayout_popup, base);

final PopupWindow pup = new PopupWindow(pupLayout, android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);

int x = location[0] - (int) ((pupLayout.getWidth() - v.getWidth()) / 2 ); // --> pupLayout.getWidth() gives back -2?
int y = location[1] + v.getHeight() + 10;

pup.setFocusable(true);
pup.showAtLocation(v, Gravity.NO_GRAVITY, x, y);
}


Has anybody an idea to get measures?

Thanks ;)

Answer

You won't get the height or width of the view, which hasn't been drawn on the screen.

pupLayout.getWidth() // this will give you 0

You need to get the width like this

int width = MeasureSpec.makeMeasureSpec(0, MeasureSpec. UNSPECIFIED);

Use it like this

View pupLayout = inflater.inflate(R.layout.linearlayout_popup, base);
pupLayout.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

int x = location[0] - (int) ((pupLayout.getMeasuredWidth() - v.getWidth()) / 2 );