Android's viewDidLoad and viewDidAppear equiva

2019-02-02 04:17发布

问题:

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?

回答1:

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;
        }
    });


回答2:

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.



回答3:

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.