Two days ago I had to work with some views (Surprise! Surprise!). At some point I had to get the actual views’ width and height, before actually displaying the views. Of course, they were included in my XML layout. Thus this made the task a little bit easier. After spending several minutes on Google (ALWAYS do that, when you are in trouble), I found a solution.

Code Description:

You can see that we can actually obtain the view’s dimensions thanks to the Display class. By using it we can get information about the size and density of the current logical display. Now, a logical display DOES NOT necessary represents an actual physical display. There can be a difference between these two.

After obtaining an instance of the Display class and finding the view we need, we must call the measure() method of that view. The actual implementation of it is not relatively simple, but the overall idea is that it calculates how big the view should be.

The only thing left is to call getMeasuredWidth() & getMeasuredHeight(). These two methods return the raw width and height sizes of our view.

References

Feel free to share, comment & give your opinion on the topic!