Reputation: 4908
In my application, I have an Activity. That Activity has 5 fragments. Each Fragment occupies the whole window and at anytime only one of them will be shown.
From the fifth fragment I'm opening the camera to take a picture. Since I'm opening camera, in some phones the Activity got killed and recreated.
After capturing photo, the result is given to the newly created Activity. But since this is a newly created one, this one shows the First fragment instead of Fifth.
How can I show the fifth Fragment with maintaining its state? setRetainInstance is useful only if the Activity got recreated on configuration changes.
The main problem is, at that time Activity recreation, those fragments' default constructor gets called and resulting in duplicate instance of all fragments.
Upvotes: 1
Views: 1012
Reputation: 13390
How can I show the fifth Fragment with maintaining its state? setRetainInstance is useful only if the Activity got recreated on configuration changes.
As one of the answers mentioned, you can just use an index and save it in onSaveInstanceState and then use that later.
The main problem is, at that time Activity recreation, those fragments' default constructor gets called and resulting in duplicate instance of all fragments.
Its the default behaviour. System destroyed your fragments, system will create them again using a default constructor. Duplicate will occur if you also create new fragment. To avoid that, simply check if a fragment is already existing in fragment manager.
e.g
if(getSupportFragmentManager().findFragmentByTag(tag5th) == null)
create your fragment and add in fragment transaction
else
use this fragment from fragment manager
Upvotes: 0
Reputation: 34
Try to save your fragments state in onSaveInstanceState() and inside onCreate use it to restore the state.
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "fragment", currentFragment);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Load saved fragment or values you want
currentFragment = getSupportFragmentManager().getFragment(savedInstanceState, "fragment");
} else {
// your code to initialize all the fragments (App Launch case)
}
}
This will still maintain the state and will give call back to onActivityResult.
Upvotes: 1