get the latest fragment in backstack

后端 未结 17 2104
长发绾君心
长发绾君心 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条回答
  •  旧时难觅i
    2020-11-27 11:47

    I personnaly tried many of those solutions and ended up with this working solution:

    Add this utility method that will be used several times below to get the number of fragments in your backstack:

    protected int getFragmentCount() {
        return getSupportFragmentManager().getBackStackEntryCount();
    }
    

    Then, when you add/replace your fragment using FragmentTransaction method, generate a unique tag to your fragment (e.g.: by using the number of fragments in your stack):

    getSupportFragmentManager().beginTransaction().add(yourContainerId, yourFragment, Integer.toString(getFragmentCount()));
    

    Finally, you can find any of your fragments in your backstack with this method:

    private Fragment getFragmentAt(int index) {
        return getFragmentCount() > 0 ? getSupportFragmentManager().findFragmentByTag(Integer.toString(index)) : null;
    }
    

    Therefore, fetching the top fragment in your backstack can be easily achieved by calling:

    protected Fragment getCurrentFragment() {
        return getFragmentAt(getFragmentCount() - 1);
    }
    

    Hope this helps!

提交回复
热议问题