I think you should go back to your original code for this use case - if you just want to show a gallery of images, it is much simpler to build a ViewPager based on Views rather than Fragments. You would typically use Fragments when you have more complicated screens for each page, e.g. if the ViewPager was the top-level navigation UI.
There is a pretty old but still relevant article on the problems you can run into with static Drawable references. Drawables have references to Views, which have references to an Activity. By using static Drawable references so you can easily leak the Activity context. If you support both vertical and portrait orientations, your Activity will be destroyed and recreated every time the device is rotated. You would need to be careful about how to keep your loaded bitmaps in this case (you only want to clear the array when the user is leaving the Activity, not when they are rotating).
The PagerAdapter class actually has two versions of the instantiateItem method:
- public Object instantiateItem (View container, int position)
- public Object instantiateItem (ViewGroup container, int position)
The original (#1) is deprecated in favor of the second method. When you override instantiateItem you generally need to add your View to the container. With the first method signature, you would first need to cast your container to a ViewGroup before adding. The second method signature avoids this by giving you a ViewGroup from the start. There are several similarly deprecated methods in PagerAdapter - all of them have equivalent versions that take a ViewGroup instead of a View.
Here is some (untested) sample code that implements a PagerAdapter to display images:
public class GalleryPagerAdapter extends PagerAdapter {
private Context mContext;
private BitmapDrawable[] mIcons;
public GalleryPagerAdapter(Context context, BitmapDrawable[] icons) {
mContext = context;
mIcons = icons;
}
@Override
public int getCount() {
return mIcons.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
// You can inflate a layout here instead and apply styling to the ImageView
ImageView imageView = new ImageView(mContext);
BitmapDrawable icon = mIcons[position];
imageView.setImageDrawable(icon);
container.addView(imageView, 0);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}