Frank LaRosa
Frank LaRosa

Reputation: 3623

Measure size of a view?

Can someone explain when, and how, I can measure the exact size of a view that's been inflated from an xml file?

I understand that the height and width of a view aren't going to be available immediately after I call setContentView. There must be some callback that gets called after the view is finished laying out, but I can't find anything obvious in the Activity callbacks. I'm looking for the equivalent of "viewDidLoad" in iOS programming.

I'm also somewhat unclear as to how I actually read the height and width. There are getHeight() and getWidth() functions on View, but I've also seen examples that use getLayoutParams().height and getLayoutParams().width. What is the difference between these two values and which one do I want?

My ultimate goal is to force my view into a fixed aspect ratio by modifying the width if necessary (it's a landscape oriented view). I haven't been able to find any way to do that in XML so I figured I could read the height and width at runtime, compute the right width and set it. If anyone knows a better solution, I'd appreciate it.

Thanks.

Upvotes: 2

Views: 1397

Answers (1)

stinepike
stinepike

Reputation: 54682

you can use ViewTreeObserver class. Here is a nice answer

How to retrieve the dimensions of a view?

And for the second part

LayoutParams.height is the height you wish your view will have once laid out and could be set to particular constants like WRAP_CONTENT, getHeight() returns the actual height (it returns 0 until the view isn't laid out).

Upvotes: 1

Related Questions