我使用带有FragmentPagerAdapter的ViewPager来显示来自不同文件夹(每个Fragment项目内)的图像。我遇到了FragmenPagerAdapter的奇怪行为。第一次,当我创建它时一切都很好,我可以看到图片。但是,当我第二次创建它时,我只有黑色屏幕没有图像,我需要滚动ViewPager 4次才能看到它们,而且我还看到一些带有前一个文件夹图像的碎片与当前文件夹中的图像一起出现。我的存在是因为这些碎片被缓存了吗?我试图使用FragmentStatePagerAdapter,但我没有成功。谢谢你的帮助!这是我的FragmentPagerAdatpter的代码。
public class MyPagerAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener {
private MyLinearLayout cur = null;
private MyLinearLayout next = null;
private MainActivity context;
private FragmentManager fm;
private FragmentImageList il;
private float scale;
private int size;
private ArrayList<Image> images;
public MyPagerAdapter(MainActivity context, FragmentManager fm, FragmentImageList il, ArrayList<Image> images) {
super(fm);
this.fm = fm;
this.context = context;
this.il = il;
this.images = images;
size = images.size();
}
@Override
public Fragment getItem(int position)
{
// make the first pager bigger than others
if (position == FragmentImageList.FIRST_PAGE)
scale = FragmentImageList.BIG_SCALE;
else
scale = FragmentImageList.SMALL_SCALE;
//position = position % FragmentImageList.PAGES;
position = position % size;
return FragmentImageItem.newInstance(context, position, scale, images.get(position));
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
container.removeView(((FragmentImageItem)object).getView());
}
@Override
public int getCount() {
//return FragmentImageList.PAGES * FragmentImageList.LOOPS;
return size * FragmentImageList.LOOPS;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffset >= 0f && positionOffset <= 1f){
cur = getRootView(position);
next = getRootView(position +1);
cur.setScaleBoth(FragmentImageList.BIG_SCALE
- FragmentImageList.DIFF_SCALE * positionOffset);
next.setScaleBoth(FragmentImageList.SMALL_SCALE
+ FragmentImageList.DIFF_SCALE * positionOffset);
}
}
@Override
public void onPageSelected(int position) {}
@Override
public void onPageScrollStateChanged(int state) {}
private MyLinearLayout getRootView(int position){
return (MyLinearLayout)
fm.findFragmentByTag(this.getFragmentTag(position))
.getView().findViewById(R.id.root);
}
private String getFragmentTag(int position) {
return "android:switcher:" + il.pager.getId() + ":" + position;
}
}