I am having a problem with Fragments
and orientation change.
I have an application which has a MainActivity
which handles the switching up
if(savedInstanceState == null) is not working always. sometimes savedInstanceState != null while you need to add another fragment because of landscape orientation.
Another approach is to test whether fm.findFragmentById(R.id.frameLayoutLeft), no matter what the orientation is, is null or not, if so, than create a new fragment instance otherwise do nothing. If you need a second fragment in landscape mode, you need first check whether it's landscape or not if so, check whether fm.findFragmentById(R.id.frameLayoutRight) is null or not. if null, than create, otherwise do nothing because it's already there retained by Android OS.
I had more or less the same problem, but the solutions presented above did not seem to work out in my situation. Eventually I found the following solution:
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.replace(android.R.id.content, mFragment, mTag); // Use replace iso add
}
else {
ft.attach(mFragment);
}
}
I found out that setRetainInstance
is actually ignored and all fragments created by the android.support.v4.app.FragmentManager
are stored in onSaveInstanceState
and are recreated in onCreate
.
For me the solution was to bluntly delete the superfluously saved fragment: https://stackoverflow.com/a/13996054/341091
It sounds like you don't have something in your onCreate
method wrapped in a if(savedInstanceState == null)
, so you are creating another fragment in addition to the one being restored from the savedInstanceState bundle.
EDIT
Looking more closely at your code, I think I was wrong about the onCreate, your onTabSelected should handle it. I think your if (mFragment == null)
is always coming up null, because you don't try and find the fragment. Change that code section to:
@Override
public void onTabSelected(Tab tab, android.support.v4.app.FragmentTransaction ft) {
mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag); // add this
if (mFragment == null){ // check to see if the fragment has already been initialised. If not create a new one.
mFragment = android.support.v4.app.Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content,mFragment,mTag);
} else {
ft.attach(mFragment); // if the fragment has been initialised attach it to the current activity
}
}
Short fix:
In the onTabSelected
method, before using if (mFragment == null)
you need to try to get the fragment (using mFragment = getSupportFragmentManager().findFragmentByTag(mTag)
). You can also set this from the outside but I don't see you doing this.
Checking if(savedInstanceState == null)
on onCreate
could also solve this and I consider it a better approach though! :)