Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentManager replace vs Add

Tags:

android

In my application there is a FrameLayout on which I am adding various fragments

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, fragment, fargmentTag);
ft.commit();

Now it seems when I use the ft.replace(R.id.fragment_content, fragment, fargmentTag); and then in other places call

getSupportFragmentManager().findFragmentByTag(fargmentTag); 

I always get null.

However if I use add instead of replace this problem is fixed but another problem appears that each fragment is added ontop of the other fragment and i can see the other fragments below.

I would prefer to use replace, but I need the saved fragment state. Also to be noted I am not using addToBackStack.

like image 780
user1730789 Avatar asked May 20 '13 14:05

user1730789


People also ask

Why do you need to call addToBackStack () before commit transaction?

By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.

Which method is called when fragment is replaced?

The onDetach() callback is invoked when the fragment has been removed from a FragmentManager and is detached from its host activity. The fragment is no longer active and can no longer be retrieved using findFragmentById() . onDetach() is always called after any Lifecycle state changes.

How do I know if a fragment is already added?

You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist.


1 Answers

Try this and it would work.

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, fragment, fragmentTag);
ft.commitAllowingStateLoss();
like image 66
Thalaivar Avatar answered Oct 06 '22 01:10

Thalaivar