Reputation: 11780
I have an activity with two fragments: DogFragment, LegoFragment. In portrait mode I show DogFragment and in landscape mode I show LegoFragment. My problem is that the fragments aren’t remembering their states after rotation. Is there a way to save the fragment’s states? Understand that the activity is recreated during orientation changes and that based on the orientation I create and attach either DogFragment or LegoFragment to the activity.
Here is the activity’s onCreate
method where I add the fragments.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
addDogFragment();
} else {
addLegoFragment();
}
}
private void addDogFragment() {
DogFragment fragment = DogFragment.newInstance(null, null);
getSupportFragmentManager().beginTransaction().
replace(R.id.fragment_container, fragment).commit();
}
private void addLegoFragment() {
LegoFragment fragment = LegoFragment.newInstance(null, null);
getSupportFragmentManager().beginTransaction().
replace(R.id.fragment_container, fragment).commit();
}
I know that the FragmentManager has a copy of my fragments. But I am not sure the best way to solve this problem. If I call replace
with a tag, do I just findByTag and then call replace again? Or is there a standard way to do these things?
Upvotes: 1
Views: 231
Reputation: 46
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT)
attachFragment(R.id.fragment_container, "dogFragment", DogFragment.class.getName());
else
attachFragment(R.id.fragment_container, "legoFragment", LegoFragment.class.getName());
private FragmentTransaction mCurTransaction;
private FragmentManager mFragmentManager;
public void attachFragment(int containerViewId, String tag, String fragmentClassName){
if (mFragmentManager == null)
mFragmentManager = getSupportFragmentManager(); // or getFragmentManager();
if (mCurTransaction == null)
mCurTransaction = mFragmentManager.beginTransaction();
// Do we already have this fragment?
Fragment fragment = mFragmentManager.findFragmentByTag(tag);
if (fragment != null){
mCurTransaction.attach(fragment);
}else {
fragment = Fragment.instantiate(this, fragmentClassName);
mCurTransaction.add(containerViewId, fragment, tag);
}
}
Upvotes: 0
Reputation: 8211
Try this, create a similar function for LegoFragment
private void setDogFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment removeFragment = mFragmentManager.findFragmentByTag("lego");
if (removeFragment!=null) {
transaction.detach(removeFragment);
}
Fragment fragment = mFragmentManager.findFragmentByTag("dog");
if (fragment != null) {
transaction.attach(fragment);
} else {
fragment = new DogFragment();
transaction.add(R.id.fragment_container, fragment,
"dog");
}
transaction.commit();
}
Upvotes: 1