I need a way to run some code at the exact moment in which the activity is fully loaded, laid out, drawn and ready for the user's touch controls. Which method/listener does that?
in short onCreate is called first and when you comeback from an activity onResume will be called. onResume will also be called the first time as well.
The onStop() and onDestroy() methods get called, and Android destroys the activity. A new activity is created in its place. The activity is visible but not in the foreground.
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.
Activity-lifecycle concepts To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of six callbacks: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() . The system invokes each of these callbacks as an activity enters a new state.
Commonsware is right, without explaining what your are trying to do and why, it's not possible to answer your question and I suspect, with detail, you are probably thinking about it the wrong way.
However, I do have some code where I needed to do some very funky layout stuff after everything had been measured.
I could have extended each of the view classes in the layout and overriden onMeasure()
but that would have been a lot of work. So, I ended up doing this. Not great, but it works.
mainMenuLayout is the layout I needed to get funky with. The onGlobalLayout
callback is called when the layout has completed drawing. Utils.setTitleText()
is where the funkiness takes place and as I pass mainMenuLayout to it, it has access to the position and size of all of the child views.
mainMenuLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// only want to do this once
mainMenuLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// set the menu title, the empty string check prevents sub-classes
// from blanking out the title - which they shouldn't but belt and braces!
if (!titleText.equals("")){
Utils.setTitleText(_context,mainMenuLayout,titleText);
}
}
});
I've found that if I post a Runnable
to the message queue, it will run after the content for the activity has been drawn. For example, if I want the width and height of a View
, I would do this:
view.post( new Runnable() {
@Override
public void run() {
int width = view.getWidth(); // will be non-zero
int height = view.getHeight(); // will be non-zero
}
} );
I've found success with this anytime after I call setContentView()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With