Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: method called after creation of activity interface

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?

like image 531
aveschini Avatar asked Nov 04 '13 10:11

aveschini


People also ask

Which method gets called first in Android activity?

The onStart() method runs. It gets called when the activity is about to become visible. After the onStart() method has run, the user can see the activity on the screen. The onStop() method runs when the activity stops being visible to the user.

When onStop method is called in Android?

onStop() Called when the activity is no longer visible to the user. Either because another Activity has resumed, and is covering this one, an existing activity is coming to the foreground, or the activity is about to be destroyed.

How can we call method in activity from non activity class?

use interface to communicate with activity from non activity class. create colorChange() in interface and get the instance of interface in non activity class and call that method.

Why do we need to call setContentView () in onCreate () of activity class?

onCreate() method calls the setContentView() method to set the view corresponding to the activity. By default in any android application, setContentView point to activity_main. xml file, which is the layout file corresponding to MainActivity.


2 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

                    }
                });
like image 107
A. Adam Avatar answered Nov 08 '22 18:11

A. Adam


onResume() is last, but perhaps better is onViewCreated(). Its 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
            }
        });
like image 44
Malachiasz Avatar answered Nov 08 '22 17:11

Malachiasz