Volodymyr
Volodymyr

Reputation: 1047

Add and replace fragments

I found funny things with fragments. I created activity and added two fragments:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.main, new Fragment1());
ft.add(R.id.main, new Fragment2());
ft.commit();

Then I added button with code:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main, new Fragment1());
ft.commit();

If I press first time - Fragment1 is destroying, if I press second time - Fragment2 is destroying. Why is it work so? I think that if I'm replacing fragments then container 'main' should be cleaned.

Upvotes: 0

Views: 2660

Answers (4)

Renan Bandeira
Renan Bandeira

Reputation: 3268

Take a look at the documentation

"This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here."

Upvotes: 1

user4054053
user4054053

Reputation: 1

suppose fragment f1 and f2 if u replace f2 fragment on f1 then f1 fragment onpause ondestroyview ondestroy ondetach

and f2 oncreate oncreateview onactivitycreated onstart onresume

called

if u add f2 on f1 then f1 onpause and f2 oncreate oncreateview onactivitycreated onstart onresume

are called

Upvotes: 0

kalelien
kalelien

Reputation: 432

To start, I wouldn't add two fragments to the same container. If you want to use the same container, my recommendation would be to use 2 containers both within a third container

If you need to add two fragments to the same container, you can manually get rid of them by keeping their objects around (or referencing them in some way).

For example this uses the fully qualified FragmentTransaction.add() in order to later reference the fragments

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.main, new Fragment1(), "frag1");
ft.add(R.id.main, new Fragment2(), "frag2");
ft.commit();

// Later on
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Manually remove fragments
ft.remove(getSupportFragmentManager().findFragmentByTag("frag1"));
ft.remove(getSupportFragmentManager().findFragmentByTag("frag2"));
ft.add(R.id.main, new Fragment1(), "newFrag1");
ft.commit();

From my understanding, the problem with relying on replace to get rid of multiple fragments inside the same container is that it will replace which ever is "currently showing" not the entire container (although, reading the documentation on FragmentTransaction - it certainly makes it sound like you should be able to do exactly what you are doing).

Upvotes: 1

Damien Praca
Damien Praca

Reputation: 3136

Try to use addToBackStack(null) after the replace:

ft.replace(R.id.main, new Fragment1());
ft.addToBackStack(null)
ft.commit();

Upvotes: 0

Related Questions