Setting window layout after calling setContentView()

317 views Asked by At

I am creating an activity that as a dialog format: it does not cover the whole screen, but only part of it. What I did was in the onCreate() method of this activity, after calling setContentView(), I call:

window.setLayout(windowWidthInDp, LayoutParams.WRAP_CONTENT);

And it does not work. I need to do the following instead to make it work:

window.getDecorView().post(new Runnable() { 
    @Override 
    public void run() { 
        window.setLayout(windowWidthInDp, LayoutParams.WRAP_CONTENT); 
    } 
});

Again, this is AFTER setContentView() is called. Why do I have to pose it into the message queue instead of calling it directly? Thanks!

1

There are 1 answers

4
David Wasser On BEST ANSWER

Setting the content view just gives the layout to the Android framework. The layout hasn't yet been fully configured. This doesn't happen until the Android framework gets control back (ie: in the next event loop). This won't happen until the onCreate() method ends.

By posting your code to a Handler, you delay the execution of that code until after the Android framework has fully configured the layout.