Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

android - How to keep only one instance of a fragment, when switching with NavigationDrawer?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...