I was asked what the Activity lifecycle function onStart can do, and I wondered if I could request a network. I wondered if I could request a network in onCreate or onResume, and if I could request a network in either of these methods, So what can we do in the onStart method that’s appropriate? I found a piece of code in the book Exploring Android Development Techniques
protected void onStart(a) {
super.onStart();
ViewTreeObserver observer = view.getViewTreeObserver();
observer.adddOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout(a) {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = view.gerMeasureWidth();
intheight = view.getMeasureHeight(); }}); }Copy the code
This code is used to obtain the width and height of the View.
- ViewTreeObserver class
This is done using the ViewTreeObserver’s numerous callbacks. The View has an instance of the ViewTreeObserver class. It gets this object and then adds OnGlobalLayoutListener to listen when the state of the View tree changes or the visibility of the View inside the View tree changes. The onGlobalLayout() method will be called back, so this is a good time to get the View’s width and height. The conclusion is to set the View’s listener.