I have one activity and a couple of fragments. My activity has a drawer list that I use to switch fragments and roughly looks like this:
public class MainActivity extends AppCompatActivity
{
private PreferencesFragment preferencesFragment;
private HomeFragment homeFragment;
private void selectMenuItem(position)
{
Fragment fragment = null;
switch (position) {
case 0:
if (preferencesFragment == null) {
preferencesFragment = new PreferencesFragment();
}
fragment = preferencesFragment;
break;
case 1:
if (homeFragment == null) {
homeFragment = new HomeFragment();
}
fragment = homeFragment;
break;
}
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}
}
So whenever I click on a drawer list item, selectMenuItem is called with the correct position. This loads an existing fragment or creates a new one when needed. The problem is that, even when a fragment already exists, the onCreateView method is triggered in the Fragments. I want to maintain the state of the view and only execute the code in onCreateView once. The docs say this about onCreateView:
The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
So why is it being called whenever selectMenuItem is executed? I verified that it's actually not executing the new Fragment() block and loading the properties value. How can I maintain the state of my Fragments when I'm using just 1 activity?
savedInstanceState is also null in the onCreateViewMethod in the Fragments. onSavedInstanceState is never triggered in the Fragments.