oriharel oriharel - 2 years ago 315
Android Question

Fragments onResume from back stack

I'm using the compatibility package to use Fragments with Android 2.2.
When using fragments, and adding transitions between them to the backstack, I'd like to achieve the same behavior of onResume of an activity, i.e., whenever a fragment is brought to "foreground" (visible to the user) after poping out of the backstack, I'd like some kind of callback to be activated within the fragment (to perform certain changes on a shared UI resource, for instance).

I saw that there is no built in callback within the fragment framework. is there s a good practice in order to achieve this?

Answer Source

For a lack of a better solution, I got this working for me: Assume I have 1 activity (MyActivity) and few fragments that replaces each other (only one is visible at a time).

In MyActivity, add this listener:


(As you can see I'm using the compatibility package).

getListener implementation:

private OnBackStackChangedListener getListener()
        OnBackStackChangedListener result = new OnBackStackChangedListener()
            public void onBackStackChanged() 
                FragmentManager manager = getSupportFragmentManager();

                if (manager != null)
                    MyFragment currFrag = (MyFragment)manager.


        return result;

MyFragment.onFragmentResume() will be called after a "Back" is pressed. few caveats though:

  1. It assumes you added all transactions to the backstack (using FragmentTransaction.addToBackStack())
  2. It will be activated upon each stack change (you can store other stuff in the back stack such as animation) so you might get multiple calls for the same instance of fragment.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download