Android, run code only after the UI has been rendered for an activity

You could just grab the top decor view using Window.getDecorView() and then use post(Runnable) on it. Using the decor view results in reusable code that can be run in any application as it does not depend on some specific View element being a part of the inflated layout.

The call will result in your Runnable being placed in the message queue to be run on the UI thread, so do not run long operations in the Runnable to avoid blocking the UI thread.


Simple implementation - Kotlin

// @Override protected void onCreate(Bundle savedInstanceState) {

    window.decorView.post {
        // TODO your magic code to be run
    }


Simple implementation - Java

// @Override protected void onCreate(Bundle savedInstanceState) {

    getWindow().getDecorView().post(new Runnable() {

        @Override
        public void run() {
            // TODO your magic code to be run
        }

    });

Tags:

Android