如何获得以前的片段? [英] How to get previous fragments?
问题描述
为了重用我的应用程序中的某些片段,我需要知道哪个片段是后台堆栈中的第二个片段.
In order to reuse some fragments in my app, I need to know which Fragment is the second on the back stack.
为此,我使用了 getFragmentManager().getFragments()
,它显示了以下错误(但有效!)
In order to do that I'm using getFragmentManager().getFragments()
, which shows the following error (but works!)
FragmentManager.getFragments只能从同一库组(groupId = com.android.support)中调用
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?
这是代码:
public Fragment getCallerFragment(){
List<Fragment> fragments = getFragmentManager().getFragments();
return fragments.get(fragments.size()-2);
}
推荐答案
如果我们将两个答案放在一起,则可以使用以下方法在片段中添加TAG,并使用以下方法获得先前的片段名称:
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();
}
这篇关于如何获得以前的片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!