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?

1 Answer 1

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() { ... })).

8
  • 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 5, 2012 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 9, 2012 at 18:39
  • 2
    2 lines that are worth more easy than 10 pages of documentation...simple and to-the-point...thnx... Aug 8, 2012 at 2: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 7, 2012 at 20:12
  • 10
    The fact that there is no clear and reliable callback for this purpose is a crime against all Android developers.
    – Oren
    Apr 2, 2015 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.