Android: How to get a custom View's height and width?

AndroidViews

Android Problem Overview


> Possible Duplicate:
> How to size an Android view based on its parent’s dimensions

how do I use getMeasuredWidth() and getMeasuredHeight? It always returns 0. what is the diffrence between this and getHeight() and getWidth()?

Android Solutions


Solution 1 - Android

Just got a solution to get height and width of a custom view:

@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
    super.onSizeChanged(xNew, yNew, xOld, yOld);

    viewWidth = xNew;
    viewHeight = yNew;
}

Its working in my case.

Solution 2 - Android

Don't try to get them inside its constructor. Try Call them in onDraw() method.

Solution 3 - Android

You can use the following method to get the width and height of the view, For example,

int height = yourView.getLayoutParams().height;
int width = yourView.getLayoutParams().width;

This gives the converted value of the view which specified in the XML layout.

Say if the specified value for height is 53dp in XML, you will get the converted value in integer as 80.

Solution 4 - Android

I was also lost around getMeasuredWidth() and getMeasuredHeight() getHeight() and getWidth() for a long time.......... later i found onSizeChanged() method to be REALLY helpful.

New Blog Post: how to get width and height dimensions of a customView (extends View) in Android http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html

Solution 5 - Android

The difference between getHeight() and getMeasuredHeight() is that first method will return actual height of the View, the second one will return summary height of View's children. In ohter words, getHeight() returns view height, getMeasuredHeight() returns height which this view needs to show all it's elements

Solution 6 - Android

Well getHeight gets the height, and getWidth gets the width. But you're calling those methods too soon.

If you're calling them in onCreate or onResume, the view isn't drawn yet. You have to call them after the view has been drawn.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRohith NandakumarView Question on Stackoverflow
Solution 1 - AndroidParesh MayaniView Answer on Stackoverflow
Solution 2 - AndroidMozzView Answer on Stackoverflow
Solution 3 - AndroidSamView Answer on Stackoverflow
Solution 4 - AndroidRakibView Answer on Stackoverflow
Solution 5 - AndroidOFFmindView Answer on Stackoverflow
Solution 6 - AndroidFalmarriView Answer on Stackoverflow