224

I have a custom view that draws a scrollable bitmap to the screen. In order to initialize it, i need to pass in the size in pixels of the parent layout object. But during the onCreate and onResume functions, the Layout has not been drawn yet, and so layout.getMeasuredHeight() returns 0.

As a workaround, i have added a handler to wait one second and then measure. This works, but its sloppy, and I have no idea how much i can trim the time before I end up before the layout gets drawn.

What I want to know is, how can I detect when a layout gets drawn? Is there an event or callback?

12 Answers 12

421

You can add a tree observer to the layout. This should return the correct width and height. onCreate() is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width, put this on the onCreate() method:

    final LinearLayout layout = (LinearLayout) findViewById(R.id.YOUR_VIEW_ID);
    ViewTreeObserver vto = layout.getViewTreeObserver(); 
    vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() { 
        @Override 
        public void onGlobalLayout() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    layout.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
            int width  = layout.getMeasuredWidth();
            int height = layout.getMeasuredHeight(); 

        } 
    });
19
  • 33
    Thank you very much! But I wonder why there is no simpler method for doing this because it's a common problem.
    – felixd
    Mar 16, 2014 at 0:03
  • 1
    Amazing. I tried OnLayoutChangeListener and it did not work. But OnGlobalLayoutListener worked. Thank you so much!
    – YoYoMyo
    Jan 22, 2015 at 21:57
  • 8
    removeGlobalOnLayoutListener is deprecated in API level 16.Use removeOnGlobalLayoutListener instead.
    – tounaobun
    May 20, 2015 at 3:24
  • 3
    One "gotcha" I am seeing is if your view is not visible, the onGlobalLayout is called, but later when visible the getView is called, but not the onGlobalLayout...ugh. Dec 9, 2015 at 19:53
  • 2
    Another quick solution for this is to use view.post(Runnable), it cleaner and it does the same thing.
    – dvdciri
    Jun 30, 2017 at 14:50
87

A really easy way is to simply call post() on your layout. This will run your code the next step, after your view has already been created.

YOUR_LAYOUT.post( new Runnable() {
    @Override
    public void run() {
        int width  = YOUR_LAYOUT.getMeasuredWidth();
        int height = YOUR_LAYOUT.getMeasuredHeight(); 
    }
});
10
  • 8
    I don't know if post will actually run your code after the view has already been created. There is no guarantee, since post will just add the Runnable that you create to the RunQueue, to be executed after previous queue executed on UI Thread.
    – HendraWD
    Jun 9, 2016 at 9:14
  • 7
    On the contrary, post() executes after the next UI step update, which happens after the view is created. Therefore, you are guaranteed that it will execute after the view is made.
    – Elliptica
    Jun 11, 2016 at 1:05
  • I tested this code several times, it works best only in UI-thread. In a background thread it sometimes doesn't work.
    – CoolMind
    Aug 4, 2016 at 11:00
  • 3
    @HendraWijayaDjiono, maybe this post will answer: stackoverflow.com/questions/21937224/…
    – CoolMind
    Aug 4, 2016 at 11:04
  • 1
    I ran into an issue where using the first answer wasn't working every time, using post on the view I needed to scroll (a scroll view), allowed me to scroll to the desired position correctly as soon as the view was ready to take scrollTo method calls.
    – Danuofr
    Sep 12, 2018 at 20:08
26

To avoid deprecated code and warnings you can use:

view.getViewTreeObserver().addOnGlobalLayoutListener(
        new ViewTreeObserver.OnGlobalLayoutListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    view.getViewTreeObserver()
                            .removeOnGlobalLayoutListener(this);
                } else {
                    view.getViewTreeObserver()
                            .removeGlobalOnLayoutListener(this);
                }
                yourFunctionHere();
            }
        });
2
  • 1
    In order to use this code, 'view' must be declared as 'final'.
    – BeccaP
    Mar 23, 2015 at 2:23
  • 2
    use this condition instead Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN
    – HendraWD
    Mar 4, 2016 at 9:21
13

androidx.core-ktx already has this

/**
 * Performs the given action when this view is next laid out.
 *
 * The action will only be invoked once on the next layout and then removed.
 *
 * @see doOnLayout
 */
public inline fun View.doOnNextLayout(crossinline action: (view: View) -> Unit) {
    addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
        override fun onLayoutChange(
            view: View,
            left: Int,
            top: Int,
            right: Int,
            bottom: Int,
            oldLeft: Int,
            oldTop: Int,
            oldRight: Int,
            oldBottom: Int
        ) {
            view.removeOnLayoutChangeListener(this)
            action(view)
        }
    })
}

/**
 * Performs the given action when this view is laid out. If the view has been laid out and it
 * has not requested a layout, the action will be performed straight away, otherwise the
 * action will be performed after the view is next laid out.
 *
 * The action will only be invoked once on the next layout and then removed.
 *
 * @see doOnNextLayout
 */
public inline fun View.doOnLayout(crossinline action: (view: View) -> Unit) {
    if (ViewCompat.isLaidOut(this) && !isLayoutRequested) {
        action(this)
    } else {
        doOnNextLayout {
            action(it)
        }
    }
}
12

Better with kotlin extension functions

inline fun View.waitForLayout(crossinline yourAction: () -> Unit) {
    val vto = viewTreeObserver
    vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            when {
                vto.isAlive -> {
                    vto.removeOnGlobalLayoutListener(this)
                    yourAction()
                }
                else -> viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        }
    })
}
2
  • Very nice and elegant solution that can be reused. May 8, 2020 at 7:47
  • Thanks! Agree, if we call vto.removeOnGlobalLayoutListener(this) in else branch, we will get java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver() again. Also this method didn't help in my case in BottomSheetDialog, but Handler().post helped.
    – CoolMind
    Oct 19, 2021 at 14:22
4

An alternative to the usual methods is to hook into the drawing of the view.

OnPreDrawListener is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0) or set a limit to the number of times you check for a measuredWidth greater than zero.

There is also a chance that the view will never be drawn, which may indicate other problems with your code.

final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (view.getMeasuredWidth() > 0) {     
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            //Do something with width and height here!
        }
        return true; // Continue with the draw pass, as not to stop it
    }
});
9
  • The question is How can you tell when a layout has been drawn? and you are providing a method where you call an OnPreDrawListener and don't stop interrogating that view until it has provided you with a reasonable answer so the objections to your solution should be obvious. May 14, 2019 at 14:05
  • 1
    What you need to know is not when it's been drawn but when it's been measured. My code answers the question that really needs to be asked.
    – jwehrle
    May 18, 2019 at 2:37
  • Is there some problem with this solution? Does it fail to solve the problem confronted?
    – jwehrle
    May 19, 2019 at 0:16
  • 1
    The view is not measured until it is laid out, so this alternative is excessive and performs a redundant check. You admit not addressing the question, but what you feel should be asked. The original comment made both of these points, but there are also some issues with the code itself that have been submitted as an edit. May 20, 2019 at 13:18
  • That's a nice edit. Thank you. I guess what I'm asking is, Do you think that this answer should be deleted or not? I encountered the OP's problem. This solved the problem. I offered it in good faith. Was that a mistake? Is that something that should not be done on StackOverflow?
    – jwehrle
    May 21, 2019 at 18:39
4

The most elegant way to do this is using OneShotPreDrawListener. An OneShotPreDrawListener will register a callback to be invoked when the view tree is about to be drawn and it will remove itself after one OnPreDraw call.

OneShotPreDrawListener.add(view) {
    view.doSomething();
}
3

Another answer is:
Try checking the View dimensions at onWindowFocusChanged.

2

I recommend you to use doOnLayout if you're using kotlin

doOnLayout {
    doWhateverYouNeed()
}

doc: Performs the given action when this view is laid out

1

When onMeasure is called the view gets its measured width/height. After this, you can call layout.getMeasuredHeight().

2
  • 4
    Wouldn't you have to make your own custom view to know when onMeasure fires? Sep 15, 2012 at 16:13
  • Yes, you have to use custom views to access on measure. Jun 29, 2017 at 21:08
0

I create the static variable to check if the layout was already drawn. If it was created you can simply call the function that draws.

static int firstAccess = 0;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main8);

    if (firstAccess==0) {
        LAYOUT_YOU_DRAW.post(new Runnable() {
            @Override
            public void run() {
                creatSpread();
                firstAccess = 1;
            }
        });
    }else{
        creatSpread();
    }
}
-1

view.post { TODO("Not yet implemented") }

1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    May 24, 2022 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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