Get content view size in onCreate

You can use a layout or pre-draw listener for this, depending on your goals. For example, in onCreate():

final View content = findViewById(android.R.id.content);
content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //Remove it here unless you want to get this callback for EVERY
        //layout pass, which can get you into infinite loops if you ever
        //modify the layout from within this method.
        content.getViewTreeObserver().removeGlobalOnLayoutListener(this);

        //Now you can get the width and height from content
    }
});

Update as of API 16 removeGlobalOnLayoutListener is deprecated.

Change to: content.getViewTreeObserver().removeOnGlobalLayoutListener(this)


(copied from my answer to a related question)

I use the following technique - post a runnable from onCreate() that will be executed when the view has been created:

    contentView = findViewById(android.R.id.content);
    contentView.post(new Runnable()
    {
        public void run()
        {
            contentHeight = contentView.getHeight();
        }
    });

This code will run on the main UI thread, after onCreate() has finished.

Tags:

Android