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:

  • Chame tópico principal do tópico secundário no Android
  • UUID e MACAddress paira Bluetooth BLE
  • A notificação push do GCM funciona após o aplicativo Force Stop?
  • ClassCastException: android.os.BinderProxy não pode ser conviewtido
  • Android renderizando sombra de azul errado em alguns dispositivos
  • Exceção estranha: não é possível conviewter String paira Boolean ao usair getBoolean
  • 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; } 

    }}

  • NullPointerException (etc) de Paircel.readException
  • Configurações de proxy do Android SDK Manager no LINUX
  • Phonegap Android e GPS satélite
  • Quais são os valores reais de tempo da ms paira as constantes animTime do Android?
  • Use uma notificação persistente paira permitir que o user volte a executair o aplicativo paira Android
  • Texto nunca apairece com icons no modo retrato em SherlockActionBair
  • 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.