4

I want to get the size of a view that is in my activity but I am not able to get that information in any of the activity lifecycle callbacks (onCreate, onStart, onResume). I'm assuming this is because the views have not been drawn yet. At what point are views drawn and is there a callback I can put my code so I can get the size of the view?

findViewById(R.id.header).getHeight();
Gunny
  • 164
  • 2
  • 11
  • What do you want the `height` for? – Macarse Aug 03 '10 at 17:00
  • I have a gridview with x number of componets and I want to size those componets in a way where the gridview fits on the screen without neding to scroll. It works fine in portrait mode cause i can just get the device width and divide by # of items per row. But in landscape mode i need to take the height of the device but the gridview doesnt span the whole height so i need to be able to determine the amount of space that is available for the gridview. Was planning on doing that by taking device height - bottom position of view above the gridview. This may mot be the best way. – Gunny Aug 03 '10 at 17:24

2 Answers2

3

How are views drawn provides a good overview of the process of drawing views. Basically, there is a pass where the measure what everything wants to be, and then a second pass when things are layed out.

It sounds like for your problem though, you should be able to accomplish your goal with resorting to setting height values by hand. Have you played around with the stretchMode, gravity, layoutHeight, etc of your gridview? See GridView javadoc for some details of the param choices.

Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82
  • I am trying to set the size of the gridview by hand in the java code but in order to do that I need to know how much room I have available for the gridview considering the other views in the activity but I cannot get that value so I cannot determine how to size the gridview. – Gunny Aug 03 '10 at 18:14
  • But why do you want to set the size of the gridview by hand? – Cheryl Simon Aug 03 '10 at 18:39
  • Because I am putting tiles of a game inside the gridview and scrolling takes away from the gameplay. Using a gridview was probably a mistake. I would have been better off using a TableLayout or creating a custom layout but this is my first android app and I didn't want to dive into that right away. – Gunny Aug 03 '10 at 18:48
  • 1
    I think that will be a lot easier, and work more consistantly, than trying to set the size by hand. http://developer.android.com/guide/tutorials/views/hello-tablelayout.html – Cheryl Simon Aug 03 '10 at 19:53
0

It should work in onCreate(), onStart(), and onResume() after you've instantiated your layouts. Try:

findViewById(R.id.header).getLayoutParams().height
Andy Zhang
  • 8,285
  • 1
  • 37
  • 24