Currently, with a FragmentActivity
, I toggle among 2 type of Fragments using the following code.
private void toggle() {
Fragment oldFragment = getSupportFragmentManager().findFragmentById(R.id.content);
Fragment fragment = null;
if (oldFragment instanceof ColorFragment) {
fragment = new ViewPagerFragment();
} else {
fragment = new ColorFragment(android.R.color.black);
}
getSupportFragmentManager().beginTransaction().replace(R.id.content, fragment).commitAllowingStateLoss();
}
2 Fragments are being toggle.
- ColorFragment - A simple fragment which fill up its background with solid black color.
- ViewPagerFragment - A fragment contains
ViewPager
. User can swipe between a purple color fragment, and a blue color fragment.
The code which responsible for swiping purple and blue color fragments are as below.
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return 2;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ColorFragment(android.R.color.holo_purple);
default:
return new ColorFragment(android.R.color.holo_blue_bright);
}
}
}
However, I encounter the weird behavior during toggling.
- Black color fragment was shown.
- Toggling.
- View pager, which can swipe between purple and blue fragments shown.
- Toggling.
- Black color fragment was shown.
- Toggling.
- Nothing shown, as MyFragmentPagerAdapter's getItem is not being triggered.
I think my situation is similar to FragmentPagerAdapter getItem is not called
However, I prefer not to use FragmentStatePagerAdapter
, because of the cost of potentially more overhead when switching between pages.
Any workaround to overcome this problem?
I include a complete workable source code to demonstrate this problem : https://www.dropbox.com/s/jok9tz5ktvfcteo/viewpagerbug.zip
question from:
https://stackoverflow.com/questions/15588120/fragmentpageradapter-getitem-is-not-being-triggered 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…