Reason for checking saved state in frgamentActivity oncreate ()

I study the fragments, and I checked the tutorial in the docs here with an example of the main data articles. We have 2 snippets for article titles, and when selected, a detailed view of the article is displayed (multi-page layout). I get most of the tutorial, with the exception of one small part, why they check the storedInstancestate inside the onCreate method.

so my question is about the onCreate () method of container activity. He has this check

if (savedInstanceState != null) { return; } 

When I delete this, the fragments overlap in ui. therefore, I know that this prevents it, but I do not know why? I want someone to explain this to me.

Thanks in advance.

Edit: full method

  public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); // Check whether the activity is using the layout version with // the fragment_container FrameLayout. If so, we must add the first fragment if (findViewById(R.id.fragment_container) != null) { // However, if we're being restored from a previous state, // then we don't need to do anything and should return or else // we could end up with overlapping fragments. if (savedInstanceState != null) { return; } // Create an instance of ExampleFragment HeadlinesFragment firstFragment = new HeadlinesFragment(); // In case this activity was started with special instructions from an Intent, // pass the Intent extras to the fragment as arguments firstFragment.setArguments(getIntent().getExtras()); // Add the fragment to the 'fragment_container' FrameLayout getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit(); } } 
+4
source share
2 answers

I understood.

The fact is that: the fragments contained in it are saved automatically if the activity is destroyed by the behavior of the screen rotation.

So, when the action is restored from the previous state (screen rotation), the onCreate () method is called again, which means that the fragment will be added again when the screen is rotated (in accordance with the code above). therefore, we must check inside the onCreate () method if we are restored from the rotation if (savedInstanceState != null) , so there is no need to re-add the fragment, just do nothing.

+4
source

savedInstanceState checks for the last saved state.

In android, whenever you rotate your device or return with another activity, the overall Android life cycle starts as it should, for example onCreate> onStart> onResume, etc. This means that all your activity starts with fresh ones.

But in savedInstanceState you will get the last state of your user interface that you have saved or are using.

+3
source

Source: https://habr.com/ru/post/1501444/


All Articles