Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain the Fragment object while rotating

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(); } 
like image 570
Jithin Avatar asked Mar 02 '11 06:03

Jithin


People also ask

What will happen if an activity with a retained fragment is rotated?

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 .

Is activity destroyed on rotation?

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.

Can a fragment run without activity?

Android app must have an Activity or FragmentActivity that handles the fragment. Fragment can't be initiated without Activity or FragmentActivity.

Can fragments be used in multiple activities?

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.


1 Answers

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      }  } 
like image 51
Labeeb Panampullan Avatar answered Sep 20 '22 12:09

Labeeb Panampullan