I am trying to explore about how fragments are managed by android framework and through my research I got to know so many new things that I didn't know about fragments but I got stuck at one point and can't figure out how this is happening.
Please try to understand my scenario first. It goes like that: I have one Activity which add two fragments one by one. When activity is first loaded then Fragment A is attached to it using below code:
private void initFirstFragment(){
Bundle bundle = new Bundle();
bundle.putString("TEXT_TO_SHOW", "FIRST ACTIVITY\nFIRST DUMMY FRAGMENT");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, FirstDummyFragment.newInstance(bundle), FirstDummyFragment.class.getSimpleName());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
These callback methods of Fragment A is called when it is loaded
FirstDummyFragment: onCreate: savedInstanceState--->null
FirstDummyFragment: onCreateView: savedInstanceState--->null
FirstDummyFragment: onResume
Now in Fragment A, I have a edit text and I type some text into it.
When a button is clicked inside an Activity then Fragment B is added to same container using below code:
public void openSecondFragment() {
Bundle bundle = new Bundle();
bundle.putString("TEXT_TO_SHOW", "FIRST ACTIVITY\nSECOND DUMMY FRAGMENT");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, SecondDummyFragment.newInstance(bundle), SecondDummyFragment.class.getSimpleName());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Below callback methods are called after adding Fragment B
SecondDummyFragment: onCreate: savedInstanceState--->null
FirstDummyFragment: onDestroyView
SecondDummyFragment: onCreateView
SecondDummyFragment: onResume
When I press back button, Fragment B is destroyed and Fragment A comes to foreground and below callback methods are called
SecondDummyFragment: onDestroyView
SecondDummyFragment: onDestroy
SecondDummyFragment: onDetach
FirstDummyFragment: onCreateView: savedInstanceState--->null
FirstDummyFragment: onResume
And the edit text of fragment A contains same text that I entered into it earlier before adding Fragment B. I am confused how android is restoring Fragment A's view state even if savedInstanceState is null and onCreateView returns a whole new View object when Fragment A is created again.