0

I've the fragments A -> B -> C -> D. Every fragment, with the method onCreateView, change a String variable in the main Activity. Everything works fine going from A to B or C or D, but when I press the back button - for example from C to B- I need to refresh the MainActivity's variable to the right value. How can I achieve that? onResume(), onStart(), onCreateView isn't called when I come back to previous fragments.

Edit, B C D is the same Class' fragment, and can be and fragments because I'm implementing a folder directory, with B C D sub folder directory. I cannot use tags I think, because I don't know how many fragments I have.

user3678528
  • 1,741
  • 2
  • 18
  • 24
Alessio Crestani
  • 1,602
  • 4
  • 17
  • 38

2 Answers2

2

Check out this example: https://stackoverflow.com/a/24042109/2413303

Basically, specify the resource ID in the constructor of the Fragment:

public MyFragment()
{
    super();
    titleId = R.string.drawer_myfragment_title;
}

Add the following interface (added in edit):

public interface GetActionBarTitle
{
    int getActionBarTitleId();
}

Return this with an interface:

public class MyFragment extends Fragment implements GetActionBarTitle
{
   private int titleId;

   @Override
   public int getActionBarTitleId()
   {
       return titleId;
   }
}

And in the activity, add the following to the onCreate() method:

getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
{
    public void onBackStackChanged()
    {
        int backCount = getSupportFragmentManager().getBackStackEntryCount();
        if (backCount == 0)
        {
            finish();
        }
        else
        {
            Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
            mTitle = getString(((GetActionBarTitle) fragment).getActionBarTitleId());
            getSupportActionBar().setTitle(mTitle);
        }
    }
});
Community
  • 1
  • 1
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
0

You can declare method in YourActivity for refresh.

And in fragment just cast Activity to yours and call method.

For example, in YourActivity declare method:

public void refreshMe(){
...
}

So, in your fragment you can call:

((YourActivity)getActivity()).refreshMe();