Search code examples
androidandroid-fragmentsback-stack

Event for Fragment restoring from BackStack


I attach SessionFragment from SpeakerFragment with code:

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .add(R.id.container, new SessionFragment(session))
                .addToBackStack("session")
                .commit();

In SessionFragment (in OnAttach()) I change ActionBar title to Session title.

When return back from SessionFragment, I want change ActionBar title to Speaker name. How can I do that?

OnStart(), OnResume(), onAttach() not calling.


Solution

  • You just added a fragment to the container without detaching or removing the previous one, try replace instead and set your ActionBar title in OnActivityCreated()

    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, new SessionFragment(session))
            .addToBackStack("session")
            .commit();
    

    Another note, you shouldn't use a non-empty Constructor for Fragments, as the framework will only call the empty constructor when restoring a fragment e.g. after idling, background etc. Instead session's class should implement parcelable, and should be passed as fragment argument using fragment.setArguments().