Home » Android » Android: method called after creation of activity interface

Android: method called after creation of activity interface

Posted by: admin June 15, 2020 Leave a comment

Questions:

I would like to perform some task after the creation of the graphic interface of the activity. I need to know the exact height and width of some views and change the layoutParams of some of those views based on the width and height. In the onResume method the views have all the parameters still equal to 0…

As for now I’m using a delayed task that runs after some time from the onCreate but this isn’t a good solution at all…

What is the last method called in the activity creation? And are the views’ width and height available in such method?

How to&Answers:

Call this inside of the onCreate()

       final View rootView = getWindow().getDecorView().getRootView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(
                new ViewTreeObserver.OnGlobalLayoutListener() {

                    @Override
                    public void onGlobalLayout() {

                        //by now all views will be displayed with correct values

                    }
                });

Answer:

onResume() is last, but perhaps better is onViewCreated(). It’s advantage is that it is not invoked every time you regain focus. But try getting properties of your view inside of post() over layout element which you need. For example:

        textView.post(new Runnable() {
            @Override
            public void run() {
                 // do something with textView
            }
        });

Answer:

The last method that runs when activity starts is onResume().
You can find it at Activity lifecycle.

If that is not good enough for you, run delayed task from this onResume() and you’ll be fine.

Answer:

In the last line of the onResume() method get all the data you want. It should show you all that you need.