I have developed an app in Honeycomb and I am using fragments.
This is my app
- I have an Activity (Say A1) and in that there is a fragment
- Initially this fragment hold the object one fragment object say (F1)
- Then depending on the user actions it may change to other objects F2,F3 ....
What my problem is
When The user rotate the device the activity is recreated and which make F1 as the fragment object even though before rotating it wasn't
What is the way to retain the fragment object while rotating?
I used setRetainInstance(true);
but it didn't work for me
And I have added the fragment by code in my onCreate
function like this
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Fragment homeFragment = new Home();
fragmentTransaction.add(R.id.mainFragement, homeFragment);
fragmentTransaction.commit();
}
By default Android will retain the fragment objects. In your code you are setting the
homeFragment
in youronCreate
function. That is why it is allways somehomeFragment
orfl
what ever that you set inonCreate
.Because whenever you rotate, the onCreate will execute and set your fragment object to the first one
So the easy solution for you is check whether
savedInstanceState
bundle is null or not and set the fragment objectI defined a
Fragment
in activity's layout,onSaveInstanceState
in theFragment
does get called, but thesavedInstanceState
Bundle
in the Fragment'sonCreatView
comes as null.The reason was that my
Fragment
did not have a ID in XML:You need to give your Fragment a unique tag, and check whether this Fragment is already added to your Activity already or not.
Checking whether
savedInstanceState
is null is not a safe way to check whether your fragment is already set - it will work in most cases, but in some cases (such as when the device is on low memory), Android may kill your Activity, which could break your application.To see this in action, tick "Don't keep activities" in the device's development options (the setting is available in Android 4.0+, not sure about earlier versions). When you open a new activity, your first activity is destroyed. When you return to it (by pressing back), it is created again, and savedInstanceState is not null. However, your fragment is not in the activity anymore, and you have to add it again.
EDIT - Showing the original principle but with SupportFragmentManager
this comes in especially useful if you want to manipulate the fragment (in this case
mHomeFragment
) after rotating your deviceYou can simply set the
RetainInstance
property insideOnCreate
of the fragment class.Retain the Fragment object while rotating
Use
onAttachFragment()
in yourActivity
to reassign the object: