I have developed an app in Honeycomb and I am using fragments.
This is my app
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'tWhat 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(); }
Fragments — Scenario 3: Activity with retained Fragment is rotated. The fragment is not destroyed nor created after the rotation because the same fragment instance is used after the activity is recreated. The state bundle is still available in onActivityCreated .
When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.
Android app must have an Activity or FragmentActivity that handles the fragment. Fragment can't be initiated without Activity or FragmentActivity.
You can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment.
By default Android will retain the fragment objects. In your code you are setting the homeFragment
in your onCreate
function. That is why it is allways some homeFragment
or fl
what ever that you set in onCreate
.
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 object
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(null == savedInstanceState) { // set you initial fragment object } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With