1

I am using Fragment activity and a number of fragments to get added and poped out on back press.

Supposed I am adding Fragment B from Fragment A. The title of action bar that I set in A changes by navigating to B; but it is not restoring to A when I pop the fragment B out of the fragment stack as onResume of fragment is not being called.

I am using the code:

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().add(R.id.container, fragmentToReplace, tag).addToBackStack(tag).commit();

and to pop out the last fragment:

fragmentManager.popBackStack();

How to manage this. Please suggest.

2 Answers2

0

You can use onBackStackChanged listener which will be called whenever a fragment is popped back. To add the listener use this:

 getFragmentManager().addOnBackStackChangedListener(this);

In Override function, check the fragment which is popped and according to it you can change the actionbar title:

  @Override
public void onBackStackChanged() {
  //Check the fragment from the FrameLayout Container R.id.container
  // Depending on the Fragment you can change the Title
  setTitle("xyz");    
   }
Kushal
  • 8,100
  • 9
  • 63
  • 82
0

Create new class in your package and extend with Fragment says TestFragment and create abstract method in it

abstract public String getTitle();

than extend your every fragment with TestFragment and override getTitle() in your fragments.

public String getTitle(){
      return "YOUR_FRAGMENT_NAME";
}


getSupportFragmentManager().addOnBackStackChangedListener(
                new OnBackStackChangedListener() {

                    @Override
                    public void onBackStackChanged() {
                        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.content_frame);
                        this.setTitle(fragment.getTitle());
                    }
                });
Haris Qurashi
  • 2,104
  • 1
  • 13
  • 28