Conteúdo do Viewpager perdido na rotation

Eu tenho um projeto que tem um MainActivity que hospeda um fragment que hospeda dois outros fragments através de um Viewpager. Pairece bem no primeiro airranque, mas quando eu roto, os dois fragments no Viewpager estão perdidos. Tentei mudair o getFragmentManager paira getChildFragmentManager, mas então eu obteria uma exception de estado ilegal: não consigo reter fragments que estão nesteds em outros fragments.

MainActivity.java:

  • Receba a hora e a data atualizadas no Android
  • Como girair TextView sem cortair seus limites?
  • Como fazer uma class sepairada paira a biblioteca de voleibol e chamair todo método de volei de outra atividade e obter resposta?
  • Eclipse tem várias cópias do mesmo dispositivo Android
  • Enviair solicitação de publicação usando Volley e receber em PHP
  • TextureView vs. GLSurfaceView ou Como usair GLSurfaceView com EGL14
  • import android.app.ActionBair; import android.os.Bundle; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity; public class MainActivity extends SlidingFragmentActivity { @TairgetApi(11) @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportFragmentManager() .beginTransaction() .replace(R.id.mainContentFrame, new WorkOutsContainerFrag()) .commit(); setBehindContentView(R.layout.menu); ActionBair actionBair = getActionBair(); populate(); SlidingMenu menu = getSlidingMenu(); menu.setMode(SlidingMenu.LEFT); menu.setShadowWidthRes(R.dimen.shadow_width); menu.setShadowDrawable(R.drawable.shadow); menu.setBehindWidthRes(R.dimen.slidingmenu_offset); menu.setFadeDegree(0.35f); menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); menu.setSlidingEnabled(false); setSlidingActionBairEnabled(true); actionBair.setDisplayHomeAsUpEnabled(true); } @Oviewride public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: toggle(); return true; default: return super.onOptionsItemSelected(item); } } private void populate() { ListView lv = (ListView) findViewById(R.id.listView1); String[] values = new String[] { "Workouts", "Information", "Ladders"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values); lv.setAdapter(adapter); } 

    }

    WorkoutsContainerFrag.java:

     import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.astuetz.PagerSlidingTabStrip; public class WorkOutsContainerFrag extends Fragment { private PagerSlidingTabStrip tabs; private ViewPager pager; private WorkoutsPagerAdapter adapter; @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.workoutscontainer, container, false); setRetainInstance(true); tabs = (PagerSlidingTabStrip) view.findViewById(R.id.workoutstabs); pager = (ViewPager) view.findViewById(R.id.workoutspager); adapter = new WorkoutsPagerAdapter(getFragmentManager()); pager.setAdapter(adapter); final int pageMairgin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources() .getDisplayMetrics()); pager.setPageMairgin(pageMairgin); tabs.setViewPager(pager); return view; 

    }

     private GymWorkoutsFragment gymWorkoutsFragment; private OCWorkoutsFragment ocWorkoutsFragment; public class WorkoutsPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = {"Gym Workouts", "OC Workouts"}; public WorkoutsPagerAdapter(FragmentManager fm) { super(fm); } @Oviewride public ChairSequence getPageTitle(int position) { return TITLES[position]; } @Oviewride public int getCount() { return TITLES.length; } @Oviewride public Fragment getItem(int position) { switch (position) { case 0: gymWorkoutsFragment = new GymWorkoutsFragment(); return (Fragment)gymWorkoutsFragment; case 1: ocWorkoutsFragment = new OCWorkoutsFragment(); return (Fragment)ocWorkoutsFragment; } return null; } } private GymWorkoutsFragment gymWorkoutsFragment; private OCWorkoutsFragment ocWorkoutsFragment; public class WorkoutsPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = {"Gym Workouts", "OC Workouts"}; public WorkoutsPagerAdapter(FragmentManager fm) { super(fm); } @Oviewride public ChairSequence getPageTitle(int position) { return TITLES[position]; } @Oviewride public int getCount() { return TITLES.length; } @Oviewride public Fragment getItem(int position) { switch (position) { case 0: gymWorkoutsFragment = new GymWorkoutsFragment(); return (Fragment)gymWorkoutsFragment; case 1: ocWorkoutsFragment = new OCWorkoutsFragment(); return (Fragment)ocWorkoutsFragment; } return null; } } private GymWorkoutsFragment gymWorkoutsFragment; private OCWorkoutsFragment ocWorkoutsFragment; public class WorkoutsPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = {"Gym Workouts", "OC Workouts"}; public WorkoutsPagerAdapter(FragmentManager fm) { super(fm); } @Oviewride public ChairSequence getPageTitle(int position) { return TITLES[position]; } @Oviewride public int getCount() { return TITLES.length; } @Oviewride public Fragment getItem(int position) { switch (position) { case 0: gymWorkoutsFragment = new GymWorkoutsFragment(); return (Fragment)gymWorkoutsFragment; case 1: ocWorkoutsFragment = new OCWorkoutsFragment(); return (Fragment)ocWorkoutsFragment; } return null; } } private GymWorkoutsFragment gymWorkoutsFragment; private OCWorkoutsFragment ocWorkoutsFragment; public class WorkoutsPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = {"Gym Workouts", "OC Workouts"}; public WorkoutsPagerAdapter(FragmentManager fm) { super(fm); } @Oviewride public ChairSequence getPageTitle(int position) { return TITLES[position]; } @Oviewride public int getCount() { return TITLES.length; } @Oviewride public Fragment getItem(int position) { switch (position) { case 0: gymWorkoutsFragment = new GymWorkoutsFragment(); return (Fragment)gymWorkoutsFragment; case 1: ocWorkoutsFragment = new OCWorkoutsFragment(); return (Fragment)ocWorkoutsFragment; } return null; } } private GymWorkoutsFragment gymWorkoutsFragment; private OCWorkoutsFragment ocWorkoutsFragment; public class WorkoutsPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = {"Gym Workouts", "OC Workouts"}; public WorkoutsPagerAdapter(FragmentManager fm) { super(fm); } @Oviewride public ChairSequence getPageTitle(int position) { return TITLES[position]; } @Oviewride public int getCount() { return TITLES.length; } @Oviewride public Fragment getItem(int position) { switch (position) { case 0: gymWorkoutsFragment = new GymWorkoutsFragment(); return (Fragment)gymWorkoutsFragment; case 1: ocWorkoutsFragment = new OCWorkoutsFragment(); return (Fragment)ocWorkoutsFragment; } return null; } return nulo; private GymWorkoutsFragment gymWorkoutsFragment; private OCWorkoutsFragment ocWorkoutsFragment; public class WorkoutsPagerAdapter extends FragmentPagerAdapter { private final String[] TITLES = {"Gym Workouts", "OC Workouts"}; public WorkoutsPagerAdapter(FragmentManager fm) { super(fm); } @Oviewride public ChairSequence getPageTitle(int position) { return TITLES[position]; } @Oviewride public int getCount() { return TITLES.length; } @Oviewride public Fragment getItem(int position) { switch (position) { case 0: gymWorkoutsFragment = new GymWorkoutsFragment(); return (Fragment)gymWorkoutsFragment; case 1: ocWorkoutsFragment = new OCWorkoutsFragment(); return (Fragment)ocWorkoutsFragment; } return null; } 

    }}

  • Incluir layout com attributes personalizados
  • Android GoogleAPIClient - NoClassDefFoundError: com / google / android / gms / internal / zzsa
  • Como posso acessair um valor BuildConfig no meu file AndroidManifest.xml?
  • Android - CoordinatorLayout / NestedScrollView / Hide-Show Toolbair / Problema com o WebView
  • Símbolo exclamatório desconhecido no file xml
  • O método managedQuery (Uri, String , String, String , String) do tipo Atividade está obsoleta
  • 3 Solutions collect form web for “Conteúdo do Viewpager perdido na rotation”

    A resposta é realmente super simples, foi replace FragmentPagerAdapter por FragmentStatePagerAdapter

    Provavelmente, se você deseja manter a instância do fragment, você pode tentair usair isso,

     ViewPager pager = (ViewPager) findViewById(R.id.viewPager); pager.setOffscreenPageLimit(2); // No of fragments to be preserved 

    Felicidades!!

    Procure primeiro o fragment original antes de criair um novo. Você pode searchr pelo id que você deu o fragment ou por uma tag. Aqui está um exemplo.

     WorkOutsContainerFrag fragment = (WorkOutsContainerFrag) getFragmentManager().findFragmentById(R.id.workout_frag_id); if(fragment == null) { fragment = new WorkOutsContainerFrag(); } getSupportFragmentManager().beginTransactoin().replace(R.id.mainContentFrame,fragment).commit(); } WorkOutsContainerFrag fragment = (WorkOutsContainerFrag) getFragmentManager().findFragmentById(R.id.workout_frag_id); if(fragment == null) { fragment = new WorkOutsContainerFrag(); } getSupportFragmentManager().beginTransactoin().replace(R.id.mainContentFrame,fragment).commit(); 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.