Dragon warrior Dragon warrior - 1 year ago 57
Android Question

Is there a way to get fragment from top of stack?

I have a ListFragment in my MainActivity. Here is how I set my fragment object.

FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new MyFragment();
fragmentTransaction.replace(R.id.framecontainer, newFragment, "tag");

The problem is when the user press back button, I have to, at least, change the action bar and menu by calling


I have to know what kind of fragment is showing currently, so that I know how to set the action bar. I store the setting option in fragment as arguments.

String title = fragment.getArguments().getString("KEY_TITLE");
boolean isEnabled = fragment.getArguments().getBoolean("KEY_ISENABLED");

I do search the related question, and I realized I could get the fragment by calling

MyFragment fragment = (MyFragment) getSupportFragmentManager()

However, I have to store all the tag in a custom stack, and call pop() everytime when user pressed back button in onBackPressed();

So, my question is that is there a way for me to get the current visible fragment from the stack directly?

Note: Please keep in mind that the fragment types are different, not just only MyFragment.

Answer Source

Some thing like this should help your activity figure this out on backpress:

private Fragment getCurrentFragment(){
    FragmentManager fragmentManager = getSupportFragmentManager();
    String fragmentTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName();
    Fragment currentFragment = fragmentManager
    return currentFragment;

public void onBackPressed() {
    Fragment fragmentBeforeBackPress = getCurrentFragment();
    // Perform the usual back action
    Fragment fragmentAfterBackPress = getCurrentFragment();

Hope this helps.