Barry Fruitman Barry Fruitman - 9 months ago 55
Android Question

How to get or compute the width/height of an inflated view

How do I compute the width and height of an inflated View if the parent is a PopupWindow, not a ViewGroup? I cannot use

LayoutInflator.inflate(int resId, ViewGroup parent, attachToRoot boolean)
because PopupWindow is not a ViewGroup, so I use
LayoutInflator.inflate(int resId)
instead, but after that I getWidth() and getHeight() return zero :(

I need to resize the PopupWindow to fit the View, but cannot do so until the View has a parent. Do I have a chicken-and-egg problem?

By the way the View is a subclass of RelativeView so calculating it manually is essentially out of the question.

Thanks in advance,

Answer Source

Actually popupWindow supports "wrap content" constans, so if you want popup be exact as your view - use this:

popup = new PopupWindow(context);

--other options--

getWidth() and getHeight() returns zero, because view have size only after drawing on the screen. You can try to get values from LayoutParams of inflated view.

If there is fill_parent value - you are in egg-chicken situation.

If there is values in px or dp you can manually calculate size in pixels:

Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpSize, context.getResources().getDisplayMetrics()));

If there is wrap_content value - you can use view.measure() method - all children and view itself will be measured, and you can get view.getMeasuredHeight() and view.getMeasuredWidth().