1

I'm creating a custom component, where can I know the dimensions this can assume on it's parent? In Layout it's defined with fill_parent x fill_parent.

I tried getWidth() x getHeight() on the constructor, on the onMeasure method and onFinishInflate, in all cases this return 0, I wish to know the size it's have to draw some components in independent screen size.

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167

2 Answers2

2

You can override onMeasure() and get values from there.

http://developer.android.com/reference/android/view/View.html#onMeasure(int, int)

In onMeasure you can actually set your own dimensions for the component and build component accordingly to sizes after that.

Use View.MeasureSpec.getSize(one of the parameters methods takes in. Either width, or height) to get dimensions.

carvaq
  • 1,816
  • 3
  • 16
  • 21
Alex Orlov
  • 18,077
  • 7
  • 55
  • 44
  • The value of the first param is 1073742304 and from the second is 1073742678. I'm pretty sure my screen is a lot smaller. – Marcos Vasconcelos Feb 15 '11 at 13:27
  • It's because you are given special type of parameter: http://developer.android.com/reference/android/view/View.MeasureSpec.html Just use convenience methods on your in parameters to get what you want – Alex Orlov Feb 15 '11 at 13:29
1

getWidth() and getHeight() will only be populated after the Layout Phase, that is after onLayout() has been called.

You should not use the values within onMeasure() or getMeasuredWidth()/getMeasuredHeight(), since those are only the dimensions the View is initially offered or would like to have, not necessarily the ones it actually ends up getting.

See http://developer.android.com/guide/topics/ui/how-android-draws.html for more information.

Timo Ohr
  • 7,947
  • 2
  • 30
  • 20