get the latest fragment in backstack

后端 未结 17 2054
长发绾君心
长发绾君心 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 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 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;
    }
    

提交回复
热议问题