How to get previous fragments?

时光怂恿深爱的人放手 提交于 2019-12-23 10:21:01

问题


In order to reuse some fragments in my app, I need to know which Fragment is the second on the back stack.

In order to do that I'm using getFragmentManager().getFragments(), which shows the following error (but works!)

FragmentManager.getFragments can only be called from within the same library group (groupId=com.android.support)

Is it safe to use? Could I get the same result by another approach?

Here is the code:

public Fragment getCallerFragment(){
    List<Fragment> fragments = getFragmentManager().getFragments();
    return fragments.get(fragments.size()-2);
}

回答1:


If we put both answers together, you can add TAG's to your fragments and get the previous Fragment name with this method:

private String getCallerFragment(){
        FragmentManager fm = getFragmentManager();
        int count = getFragmentManager().getBackStackEntryCount();
        return fm.getBackStackEntryAt(count - 2).getName();
    }



回答2:


Use this method to get the number of counts in backStack

getBackStackEntryCount()

use this method to get the fragments

getBackStackEntryAt (int index)

you can also do something like

FragmentManager fm = getFragmentManager();

for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
   Log.i(TAG, "Found fragment: " + fm.getBackStackEntryAt(entry).getId());
}



回答3:


You can also put tag's / id's to fragments and get them by id

val fragment = supportFragmentManager.findFragmentByTag(tag)

else Nouman Ch solution will work for you.



来源:https://stackoverflow.com/questions/46324922/how-to-get-previous-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!