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
.
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.
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.
You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist.
Try this and it would work.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, fragment, fragmentTag);
ft.commitAllowingStateLoss();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With