tags:

views:

54

answers:

2

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();
A: 

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

findViewById(R.id.header).getLayoutParams().height
Andy Zhang
That returned a -2 for the height. I am definitely calling setContentView() before trying to get the height. Is there anything else I need to do?
Gunny
Hmm.. let me do a little more research; will get back to you.
Andy Zhang
+1  A: 

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.

Mayra
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
But why do you want to set the size of the gridview by hand?
Mayra
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
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
Mayra