Problems With Fragment Lifecycle And Oncreate Being Called On Non Existent Fragment
I am testing fragments in Android and I'm having some confusing behavior with Fragment life cycle. I have a activity that uses layouts in xml for both landscape and portrait mode
Solution 1:
When you rotate the screen, Android saves your fragments in a Bundle and recreates them when it recreates the activity. That is why you get calls to a non-existing (actually just invisible) fragment. You need to handle this situation in the fragment code, or simply have both fragments in the land and port layouts, where you set the fragment visibility to GONE
if you don't need it.
A simple way to check if the fragment is visible in code is this:
@OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
returnnull;
}
}
If container
is null, your fragment is being re-created from a Bundle and won't be shown (since there is no container). You then have to check whether getView()
is null and short-circuit your code accordingly. This can get messy though, so beware :)
Post a Comment for "Problems With Fragment Lifecycle And Oncreate Being Called On Non Existent Fragment"