Orientation change from one fragment to another.
Orientation 1 (Landscape to Portrait):
- onSaveInstanceState() of fragment 1.
- onSaveInstanceState() of fragment 2.
- onStop() of fragment 2.
- onDestroy() of fragment 1.
- onDetach() of fragment 1.
- onAttach() of fragment 2.
- onCreateView() of fragment 2.
- onStart() of fragment 2.
Orientation 2 (Portrait to Landscape back):
- onSaveInstanceState() of fragment 1.
- onSaveInstanceState() of fragment 2.
onSaveInstanceState() of fragment 1.
- onStop() of fragment 2.
- onDestroy() of fragment 1.
- onDetach() of fragment 1.
onDestroy() of fragment 1.
onDetach() of fragment 1.
- onAttach() of fragment 2.
- onCreateView() of fragment 2.
- onStart() of fragment 2.
So as you notice that when I come back to fragment 1, the onSaveInstanceState(), onDestroy() and onDetach()
are called two times for second orientation successive change.
Like that it keeps on increasing with every orientation change.
My activity code:
I am adding the fragment like this-
Fragment1 firstFragment = new Fragment1();
Bundle bundle = new Bundle();
firstFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.replace(R.id.article_fragment, firstFragment)
.addToBackStack(null).commit();
UPDATE:
So what is happening is whenever I click on any tab, the addToBackStack
adds the tabbed fragment into the container decreasing the memory and calling repeated life cycle methods.
Any way to effectively check if the fragment already exist then remove previous and add the current one ?
NOTE:
I tried --
if(savedInstanceState == null) { /*Add fragment*/ }
Fragment1 fragment = (Fragment1) getSupportFragmentManager().findFragmentById(R.id.article_fragment); //if (fragment == null) { /*Add fragment*/ }
These aren't clean solutions causing other problems.