user3793870 user3793870 - 1 year ago 87
Android Question

Get the current visible Fragment Android

I've the fragments A -> B -> C -> D. Every fragment, with the method

, 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 Source

Check out this example:

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

public MyFragment()
    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;

   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)
            Fragment fragment = getSupportFragmentManager().findFragmentById(;
            mTitle = getString(((GetActionBarTitle) fragment).getActionBarTitleId());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download