我創建了一個使用FragmentStatePagerAdapter
提供小型圖庫的活動。但是,當活動恢復時(例如,從其他活動返回後),我無法恢復它。每次前兩張照片都是空白的,只有在我將兩張照片刷到一邊後,纔會刷新。我找到工作的答案(尤其是壓倒一切的getItemPosition()
)的無在恢復活動時刷新FragmentStatePagerAdapter上的圖像
我把它像這樣:
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()
),但沒有結果。我對此感到絕望。
你是個天才!我整天都在試一切,但這已經很完美了! –
與適配器的notifyDataSetChanged()調用對應。 – user465363