get the latest fragment in backstack

后端 未结 17 2043
长发绾君心
长发绾君心 2020-11-27 11:24

How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?

FragmentManager fragManager = activity.getSupport         


        
相关标签:
17条回答
  • 2020-11-27 11:59

    Kotlin

    activity.supportFragmentManager.fragments.last()
    
    0 讨论(0)
  • 2020-11-27 12:02

    this helper method get fragment from top of stack:

    public Fragment getTopFragment() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
            return null;
        }
        String fragmentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
        return getSupportFragmentManager().findFragmentByTag(fragmentTag);
    }
    
    0 讨论(0)
  • 2020-11-27 12:04

    You can use the getName() method of FragmentManager.BackStackEntry which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag).

    int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
    FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
    String tag = backEntry.getName();
    Fragment fragment = getFragmentManager().findFragmentByTag(tag);
    

    You need to make sure that you added the fragment to the backstack like this:

    fragmentTransaction.addToBackStack(tag);
    
    0 讨论(0)
  • 2020-11-27 12:06

    There is a list of fragments in the fragmentMananger. Be aware that removing a fragment, does not make the list size decrease (the fragment entry just turn to null). Therefore, a valid solution would be:

    public Fragment getTopFragment() {
     List<Fragment> fragentList = fragmentManager.getFragments();
     Fragment top = null;
      for (int i = fragentList.size() -1; i>=0 ; i--) {
       top = (Fragment) fragentList.get(i);
         if (top != null) {
           return top;
         }
       }
     return top;
    }
    
    0 讨论(0)
  • 2020-11-27 12:08

    The answer given by deepak goel does not work for me because I always get null from entry.getName();

    What I do is to set a Tag to the fragment this way:

    ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
    

    Where ft is my fragment transaction and FRAGMENT_TAG is the tag. Then I use this code to get the fragment:

    Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
    
    0 讨论(0)
提交回复
热议问题