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() ) {
transaction.show( fragment );
}
else {
transaction.add( container, fragment, tag );
}
if ( addToBackStack ) {
transaction.addToBackStack( tag );
}
transaction.commit();
// 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 use). I want to perform specific actions upon showing and hiding a certain 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 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.