tags:

views:

196

answers:

2

I need to prepare some objects based on the initial layout of widgets and views in my Activity. I'd like to do it in the initialization steps, ideally onCreate and onStart. Considering the possibility of changes that happen when we're not in the foreground, some of them might need to happen in onResume.

So I checked whether I could measure how my views had been laid out.

Log.d("MyApp", "w,h of X is " + findViewById(R.id.X).getWidth() +
      "," + findViewById(R.id.X).getHeight());

I ran this in onCreate, onStart, and onResume. Each time I get 0,0 for width, height. If I wait for onTouchEvent I get the layout information, so the layout is done by then.

I'm surprised that the layout isn't set and final by the time I'm seeing onResume. I expected the widgets to be already laid out and ready to fiddle with by then.

+1  A: 

Layout is done when you call setContentView(). If you place your Log statement after the call to setContentView() you should see the behavior you're looking for.

Mike
I'm doing setContentView in onCreate and I certainly don't have my elements laid out then. Immediately after setContentView it says "w,h of X is 0,0".
Brian
Hm, you're right. I suspect that layout isn't actually done until View.layout is called sometime later by the looper, but I don't know exactly what triggers that pass.
Mike
+2  A: 

Layout is done by the view hierarchy as needed. When your app is starting, this will be some time after onResume() (as your window is being brought up and placed on the screen). The correct way to find out about layout operations is through the various view hierarchy callbacks -- View.onSizeChanged() etc as documented under "Layout" here: http://developer.android.com/reference/android/view/View.html

hackbod
I did a stack trace on the onSizeChanged method and it does come from the message dispatch loop.
Brian