Philipp Jahoda Philipp Jahoda - 20 days ago 7
Android Question

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

I am using the following method to switch between Fragments (in my NavigationDrawer) by showing / hiding them.

protected void showFragment(int container, Fragment fragment, String tag, String lastTag, boolean addToBackStack ) {

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();

if ( lastTag != null && !lastTag.equals("")) {
Fragment lastFragment = fragmentManager.findFragmentByTag( lastTag );
if ( lastFragment != null ) {
transaction.hide( lastFragment );

if ( fragment.isAdded() ) { fragment );
else {
transaction.add( container, fragment, tag );

if ( addToBackStack ) {
transaction.addToBackStack( tag );


// set the active tag
activeFragTag = tag;

What I am unclear about is which method of the Fragments lifecycle is called when I show or hide it? (Since there is no method such as onShow() or onHide() im not quite sure what to tuse). I want to do specific actions upon showing and hiding a specific Fragment.


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 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 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.