gduh gduh - 3 months ago 10x
Android Question

Add fragment and update actionbar title

I know that question about refreshing actionbar title has already been answered.
But my problem is quiet different.

I use fragments with add method and not with replace method for some reasons. So previous fragment are not destroy and when back, previous fragment aren't not recreating.

This is my configuration :

Fragment A with title "FragA" > Fragment B with title "FragB"

When I go back to Fragment A from Fragment B the actionbar title should be "FragA" but it stay "FragB".
The problem is with add method Fragment A is not recreating and I didn't find event to refresh it.

The only simple solution I found for now is :

1- fragB.OnResume : save previous action bar title

2- fragB.OnDestroyView : restore previous actionbar title

With this solution, the result is ok, but I found this solution is not very clean. Is there a better way to refresh actionbartitle using add method with fragments ?


You can override your onBackPressed of your activity and each time you pressed it you then get the name of the fragment from the backstack to know which fragment you current at.


   public void onBackPressed() {

    int framentCount = this.getFragmentManager().getBackStackEntryCount();
    if(framentCount != 0)
        FragmentManager.BackStackEntry backEntry=getFragmentManager().getBackStackEntryAt(framentCount-1);
        String str=backEntry.getName(); //the tag of the fragment
            //set the actionbar title to FragA
        else if(str.equals("fragB"))
            //set the actionbar title to FragB

     FragA myFragA = (FragA)getFragmentManager().findFragmentByTag("MY_FRAGMENTA_A_TAG");
     if (myFragA.isVisible()) {
           //action bar.title="title first fragment"

Now to know which fragment is which you need to put a tag to your fragment when you add / replace it to the backstack. Also make sure that you call addToBackStack to put the fragments to the backstack.

FragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
FragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)