Android's viewDidLoad and viewDidAppear equivalent

Code Slinger picture Code Slinger · Aug 18, 2010 · Viewed 19.8k times · Source

Does Android have an equivalent to Cocoa's viewDidLoad and viewDidAppear functions?

If not, then how would I go about performing an action when a View appears? My app is a tabbed application, in which one of the tabs is a list of forum topics. I would like the topic list to be refreshed every time the view appears. Is such a thing possible in Android?

Answer

Rich picture Rich · Aug 18, 2010

The Activity class has onCreate and onResume methods that are pretty analagous to viewDidLoad and viewDidAppear.

Activity.onResume

EDIT

To add to this, since some have mentioned in the comments that the view tree is not yet fully available during these callbacks, there is the ViewTreeObserver that you can listen to if you need first access to the view hierarchy. Here is a sample of how you can use the ViewTreeObserver to achieve this.

    View someView = findViewById(R.id.someView);
    final ViewTreeObserver obs = someView.getViewTreeObserver();
    obs.addOnPreDrawListener(new OnPreDrawListener() {

        public boolean onPreDraw() {
            obs.removeOnPreDrawListener(this);
            doMyCustomLogic();
            return true;
        }
    });