2

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.

1
  • getLayoutParams().height will give height of the layout and getheight will give height of view Commented Mar 10, 2013 at 5:18

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.