[android] How can you tell when a layout has been drawn?

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?

This question is related to android android-layout

The answer is

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() { 
        public void onGlobalLayout() {
                } else {
            int width  = layout.getMeasuredWidth();
            int height = layout.getMeasuredHeight(); 


Similar questions with android tag:

Similar questions with android-layout tag: