只保留一个片段的实例

只保留一个片段的实例

本文介绍了如何使用NavigationDrawer切换时,只保留一个片段的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用开始于一个AddressFragment。从NavigationDrawer我开始(其中包括)一个 AddressFragment有:

My App starts with a AddressFragment. From the NavigationDrawer I start (amongst others) a new AddressFragment with:

getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, new AddressFragment())
                .addToBackStack(null)
                .commit();

但我宁愿只是回到第一个实例。我怎么能这样做呢?

But I would rather just go back the first instance. How could I do that?

或者更一般情况下,我怎么能找出来,无论是片段的实例已经存在,然后启动,如果有的话,否则创建一个?

Or more general, how can I find out, whether an instance of a fragment already exists and then start that, if yes, otherwise create one?

推荐答案

在创建片段为它设置一个标记,再后来就可以通过碎片经理找到它,并替换/创建相应。

When creating the fragment set a tag for it, then later you can find it through the fragment manager and replace/create accordingly.

FragmentManager fManager = getFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();
Fragment fragment = fManager.findFragmentByTag("uniqueTag");

// If fragment doesn't exist yet, create one
if (fragment == null) {
    fTransaction.add(R.id.fragment_list, new ListFrag(), "uniqueTag");
}
else { // re-use the old fragment
    fTransaction.replace(R.id.fragment_list, fragment, "uniqueTag");
}

这篇关于如何使用NavigationDrawer切换时,只保留一个片段的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:40