Alex Rivera | Logout

Android Honeycomb: How to change Fragments in a FrameLayout, without re-creating them?

Asked 2011-05-31T09:03:36.470
14

is it possible to switch between Fragments without re-creating them all the time? If so, how?

In the documentation I found an example of how to replace Fragments.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

But I don't want to create my Fragments from the scratch every time I need them.

I also found this example of hiding/showing Fragments:

// The content view embeds two fragments; now retrieve them and attach
// their "hide" button.
FragmentManager fm = getFragmentManager();
addShowHideListener(R.id.frag1hide, fm.findFragmentById(R.id.fragment1));
addShowHideListener(R.id.frag2hide, fm.findFragmentById(R.id.fragment2));

But how would I create a fragment with an ID outside an XML file?

I think this might be related to this question, but there isn't an answer. :/

Thank you very much in advance, jellyfish

Edit:

That's how I'm doing it now:

Fragment shown = fragmentManager.findFragmentByTag(shownFragment);

//...

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (shown != null) fragmentTransaction.hide(shown);

//switch statetement for menu sele
Edit
Report

1 Answer

4

To avoid the

IllegalStateException: Fragment already added

I found a workaround that is working fine for me: use remove(AFrag) and add(BFrag) in your transaction, instead of replace().

It looks like it is a bug: 4th comment in the accepted answer.

answered 2011-06-08T13:28:53.430

Your Answer