23

I'm trying to dynamically adjust the height of my rows depending on the (screen height - my layout height) / list.size.

Unfortunately in the onCreate method the layout height returns null (not so when i call it in an on click listener).

Is there another method I can call it in?

Macarse
  • 91,829
  • 44
  • 175
  • 230
Chr0n
  • 231
  • 1
  • 2
  • 5

1 Answers1

61

You have to wait until layout happens, which is after onCreate(). You can do so by listening to onSizeChanged() on a View or by posting a Runnable from onCreate() (myView.post(new Runnable() { ... })).

Miles
  • 31,360
  • 7
  • 64
  • 74
Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • There seems to be no listener for onSizeChanged in Android 1.6? (I even tried with new View().setOnSize... And findViewById(R.layout.main) returns null... Seems like i'm an idiot but i don't quite grasp android yet... – Chr0n Aug 31 '10 at 17:07
  • i put it on the button for which size i'm waiting meanwhile.. this.btNext.post(new Runnable() { public void run() { // Initialize tableLayout with Contacts initTableLayout(); } }); Thanks for the info. – Chr0n Aug 31 '10 at 17:14
  • 10
    Why does posting a `Runnable` to the `View` guarantee that the code within the `Runnable` will be executed after layout has happened? Is it a design feature of `View` that messages are processed out of is `Handler` once layout has occurred? – Trevor Jul 05 '12 at 11:07
  • 22
    The UI event queue will process events in order. After setContentView() is invoked, the event queue will contain a message asking for a relayout, so anything you post to the queue will happen after the layout pass. – Romain Guy Jul 09 '12 at 18:39
  • 2
    2 lines that are worth more easy than 10 pages of documentation...simple and to-the-point...thnx... – Nitin Bansal Aug 08 '12 at 02:45
  • 1
    @RomainGuy I know this post is old, but for future searches, this technique works wonderfully for most devices, but fails on Nexus S (running 2.2, and 4.0). – momo Dec 07 '12 at 20:12
  • I also used to post a Runnable to the View I want to measure, but I have some cases where getting back to a fragment after a back press, the measurement of the view still returns 0. Might be only happening in nested fragments. Can anyone confirm? – Till - Appviewer.io Feb 06 '13 at 18:30
  • 10
    The fact that there is no clear and reliable callback for this purpose is a crime against all Android developers. – Oren Apr 02 '15 at 14:20