Search code examples
androidandroid-actionbarfragmentandroid-nested-fragment

Actionbar doesnt get updated on Back press in BackStack of Nested Fragments?


I have BaseFragment which all the other fragments are extending. And base fragment OnCreate() adds custom actionbar to the application. All the child fragments update actionbar buttons and Title. On back press the actionbar doesnt get updated.

public abstract class BaseFragment extends Fragment{

     public TextView actionbarTextView;
     public Button actionbarSettings;

     public void updateActionbar(String title, boolean showSettings){
          actionbarTextView.setText(title);
          actionbarSettings.setvisibility(showSettings ? View.VISIBLE :View.GONE);
     }
}

public class ChildFragment1 extends BaseFragment{

        @override
        onResume(){
            updateActionbar("ChildFragment1",false);
        }
}
public class ChildFragment2 extends BaseFragment{

        @override
        onResume(){
            updateActionbar("ChildFragment2",true);
        }
}

Here when I got from childFragment1 -> childFragment2. On back press Title and Actionbar buttons are not updated.

How can i implement it so it always works? I am replacing fragment as below..

        Fragment newFragment = new ExampleFragment();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(true);

        // Commit the transaction
        transaction.commit();

Solution

  • You need to call getActivity().invalidateOptionsMenu(); for update your optionMenu.

    docs says : Declare that the options menu has changed, so should be recreated. The onCreateOptionsMenu(Menu) method will be called the next time it needs to be displayed