I'm working on android application that contains ViewPager
with Fragment
s, like this:
MainActivity
(MainActivityFragment
(screenSlideViewPager
(Fragment
s))), which means:
Activity
contains Fragment
contains ViewPager
contains Fragment
s
Now my problem is when rotate device or change screen rotation all Fragments in ViewPager are disappear.
any ideas to solve this issue?
EDIT 1
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentByTag(TAG) == null) {
final FragmentTransaction ft = getSupportFragmentManager()
.beginTransaction();
ft.add(android.R.id.content, new MainActivityFragment(), TAG);
ft.commit();
}
}
MainActivityFragment.java:
public class MainActivityFragment extends Fragment {
private ViewPager mPager = null;
private PagerAdapter mPageAdapter = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View reVal = inflater.inflate(R.layout.activity_main, container, false);
mPager = (ViewPager) reVal.findViewById(R.id.pagerMainContent);
mPageAdapter = new ScreenSlidePagerAdapter(getActivity().getFragmentManager());
mPager.setAdapter(mPageAdapter);
return reVal;
}
private MainGridViewFragment mainGridFragment;
private AlphabetGridViewFragment alphabetGridFragment;
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public android.app.Fragment getItem(int position) {
switch (position) {
case 1:
mainGridFragment = new MainGridViewFragment();
return mainGridFragment;
case 0:
alphabetGridFragment = new AlphabetGridViewFragment();
return alphabetGridFragment;
default:
return null;
}
}
@Override
public int getCount() {
return 2;
}
}
}
EDIT 2
Obviously MainActivity
and MainActivityFragment
are loaded, and the proof is The ActionBar
,
notice also that ViewPager
is loaded too, because you still can navigate between pages (the blue light means that the pager reached to last page) but you can't see its content.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…