Android - Fragment screen rotate

gutiory picture gutiory · Jan 27, 2012 · Viewed 38.9k times · Source

I'have 1 FragmentActivity with a ViewPager which handle 2 Fragments.

public class MyFragmentActivity extends FragmentActivity{

private Fragment f1; private Fragment f2; private ViewPager myPager; private MyFragmentAdapter mFragmentsAdapter; private static ArrayAdapter<Fragment> mFragmentArray; public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.my_layout); myViewPager = (ViewPager) findViewById(R.id.pager_acciones); mFragmentArray = new ArrayAdapter<Fragment>(getApplicationContext(),android.R.layout.simple_list_item_1); f1 = new Fragment(); f1 = new Fragment(); mFragmentArray.add(f1); mFragmentArray.add(f2); mFragmentsAdapter = new MyFragmentAdapter(getSupportFragmentManager()); myPager.setAdapter(mFragmentsAdapter); myPartidoPager.setCurrentItem(0); } public static class MyFragmentAdapter extends FragmentPagerAdapter { public AccionesFragmentAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return mFragmentArray.getCount(); } @Override public Fragment getItem(int position) { return mFragmentArray.getItem(position); } }

My problem is that every time the screen orientation changes, the activity is created and also the Fragments. I don't mind if the activity is created again, but I don't want the Fragments to be recreated.

Answer

PSchuette picture PSchuette · Oct 26, 2012

The easiest way is to throw a if statement right after the on create method is called and check to see if you already have something in there. If savedInstanceState is not null, you don't need to do anything:

if (savedInstanceState == null){
  // do whatever 
} else {
  // dont do anything
}

(this answer is more for people that stumble upon this question cause they can't figure out why fragments get re-added every time they turn their device)