user3793870 user3793870 - 6 days ago 5
Android Question

Get the current visible Fragment Android

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.

Answer

Check out this example: http://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);
        }
    }
});
Comments