Skip to content

Instantly share code, notes, and snippets.

@dominicthomas
Created August 10, 2015 15:57
Show Gist options
  • Save dominicthomas/164432506cc1a3cf8115 to your computer and use it in GitHub Desktop.
Save dominicthomas/164432506cc1a3cf8115 to your computer and use it in GitHub Desktop.
An example of a viewpager adapter that supports getting a reference to the current view. This is required as the viewpager only keeps 3 items in memory so trying to get the item using the current item index does not work.
/**
* Pager adapter to display a feed item image in a square image view
*/
public class MultipleFeedPostItemAdapter extends PagerAdapter {
private final Context mContext;
private List<FeedItem> mFeedPosts = new ArrayList<>();
private ImageView mCurrentView;
public MultipleFeedPostItemAdapter(final Context pContext, final List<FeedItem> pFeedPosts) {
mContext = pContext;
mFeedPosts = pFeedPosts;
}
@Override
public int getCount() {
return mFeedPosts.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
final SquareImageView imageView = new SquareImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
final String location = mFeedPosts.get(position).getContents().getImageLocation().getLocation();
MCImageLoader.safeGlideImageLoad(mContext, location, imageView);
container.addView(imageView, 0);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ImageView) object).setImageResource(0);
container.removeView((ImageView) object);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
mCurrentView = (ImageView)object;
}
public ImageView getCurrentView() {
return mCurrentView;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment