Dragon warrior Dragon warrior - 2 months ago 10
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");
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();


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

getActionBar().setTitle(title);
getActionBar().setDisplayHomeAsUpEnabled(isEnabled);
invalidateOptionsMenu();


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()
.findFragmentByTag("tag");


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

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
.findFragmentByTag(fragmentTag);
    return currentFragment;
}

@Override
public void onBackPressed() {
    Fragment fragmentBeforeBackPress = getCurrentFragment();
    // Perform the usual back action
    super.onBackPressed();
    Fragment fragmentAfterBackPress = getCurrentFragment();
}

Hope this helps.

Comments