Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Fragment screen rotate [duplicate]

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.

like image 412
gutiory Avatar asked Jan 27 '12 20:01

gutiory


2 Answers

You could add: android:configChanges="screenSize|orientation" In AndroidManifest.xml.

This will prevent Android calling onCreate on screen orientation change. If you want to perform special handling of orientation change, you can override onConfigurationChanges.

like image 134
Herve Thu Avatar answered Sep 19 '22 18:09

Herve Thu


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)

like image 23
PSchuette Avatar answered Sep 21 '22 18:09

PSchuette