Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android's viewDidLoad and viewDidAppear equivalent

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?

like image 851
Code Slinger Avatar asked Aug 18 '10 14:08

Code Slinger


3 Answers

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;
        }
    });
like image 197
Rich Avatar answered Nov 15 '22 15:11

Rich


onResume() is more like viewCouldAppear. :) public void onWindowFocusChanged(boolean) is the closest to viewDidAppear. At this point within the activity lifecycle you may ask the view about its size.

like image 26
Cameron Lowell Palmer Avatar answered Nov 15 '22 14:11

Cameron Lowell Palmer


From my limited, nascent understanding of Android, you implement viewDidLoad type functionality in the onCreate method of your Activity:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

The equivalent for viewDidAppear is closer to the onResume method:

Called after onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your activity to start interacting with the user. This is a good place to begin animations, open exclusive-access devices (such as the camera), etc.

like image 4
RedBlueThing Avatar answered Nov 15 '22 14:11

RedBlueThing