我创建了一个FragmentStatePagerAdapter
用于提供小画廊的活动。但是,当活动恢复时(例如,从其他活动回来后),我无法让它刷新。每次前两张图片都是空白的,只有在我将两张图片滑到一边后,它们才会刷新。我找到的答案都没有(尤其是压倒一切的getItemPosition()
)
我是这样设置的:
mPagerAdapter = new PhotosPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.photosViewPager);
mPager.setAdapter(mPagerAdapter);
然后我有 FragmentStatePagerAdapter 类:
private class PhotosPagerAdapter extends FragmentStatePagerAdapter{
public PhotosPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return photos.size();
}
@Override
public Fragment getItem(int position) {
ImageFragment f = new ImageFragment(position);
return f;
}
@Override
public int getItemPosition(Object object) {
throw new RuntimeException();
//return POSITION_NONE;
}
}
您可能已经注意到,我在 getItemPosition 中抛出 RuntimeException,因为我想检查它何时被调用。直到我添加一些包含我的图片的列表时才会调用它。然后 ImageFragment 类:
public class ImageFragment extends Fragment{
int position;
Bitmap mBitmap;
int width;
int height;
ImageView img;
public ImageFragment(){
}
public ImageFragment(int position){
this.position = position;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
img = new ImageView(container.getContext());
img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
width = container.getWidth();
height = container.getHeight();
loadBitmap();
return img;
}
public void loadBitmap(){
if (img == null){
return;
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(photos.get(position), options);
options.inSampleSize = calculateInSampleSize(options, width/2, height/2);
options.inJustDecodeBounds = false;
mBitmap = BitmapFactory
.decodeFile(photos.get(position), options);
img.setImageBitmap(mBitmap);
}
@Override
public void onDestroyView() {
mBitmap.recycle();
super.onDestroyView();
}
}
在我尝试修复它之后代码有点乱......但是:删除onDestroyView()
不起作用。我已经放置mPagerAdapter.notifyDataSetChanged()
了几个必须调用的地方(如onResume()
),但没有结果。我对此有点绝望。