Fragment lifecycle - which method is called upon show / hide? Fragment lifecycle - which method is called upon show / hide? android android

Fragment lifecycle - which method is called upon show / hide?


Similar to activity lifecycle, Android calls onStart() when fragment becomes visible. onStop() is normally called when fragment becomes invisible, but it can also be called later in time.

Depending on your layout Android can call onStart() even, when your Fragment is not yet visible, but it belongs to a visible parent container. For instance, this is valid for android.support.v4.view.ViewPager which requires you to override Fragment.setUserVisibleHint() method. In any case, if you need to register/unregister BroadcastReceivers or other listeners, you can safely use onStart() and onStop() methods because those will be called always.

Note: Some fragment containers can keep invisible fragments started. To handle this situation you can override Fragment.onHiddenChanged(boolean hidden). According to the documentation, a fragment must be both started and visible (not hidden), to be visible to the user.

Update: If you use android.support.v4.widget.DrawerLayout then a fragment below the drawer stays started and visible even when drawer is open. In this case you need to use DrawerLayout.setDrawerListener() and listen for onDrawerClosed() and onDrawerOpened() callbacks.


I @Override this method and resolve my problem:

@Overridepublic void onHiddenChanged(boolean hidden) {    super.onHiddenChanged(hidden);    if (hidden) {        //do when hidden    } else {       //do when show    }}


of course you can @Override the following method to do so:

@Override    public void setUserVisibleHint(boolean isVisibleToUser) {        super.setUserVisibleHint(isVisibleToUser);        if (isVisibleToUser) {            // Do your Work        } else {            // Do your Work        }    }