I am creating a Gallery with image and like button using Viewpager and PagerAdapter. Please refer to my code:
public class GalleryAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<MyPhotoItem> _imageCollection;
// Components in fullsceen layout
ImageView imgDisplay;
private ToggleButton btnLike;
// Variable for btnLike
private boolean isChecked;
// constructor
public GalleryAdapter(Activity activity,
ArrayList<MyPhotoItem> images) {
this._imageCollection = images;
}
@Override
public int getCount() {
return this._imageCollection.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_gallery_image,
container, false);
imgDisplay = (ImageView) viewLayout
.findViewById(R.id.layout_gallery_imgDisplay);
Picasso.with(this._activity.getApplicationContext())
.load(_imageCollection.get(position).url).into(imgDisplay);
btnLike = (ToggleButton) viewLayout
.findViewById(R.id.layout_gallery_likeButton);
btnLike.setOnCheckedChangeListener(null);
btnLike.setChecked(isChecked);
btnLike.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
isChecked = true;
} else {
isChecked = false;
}
}
});
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
@Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
}
My current issue: the Viewpager doesn't keep the toggle button state when I swiping to another pages and going back the previous ones (supposed 5 photos loaded in Viewpager). I went through a couple of Stackoverflow posts, but none of them can solve my problem properly.
Any advices will be appreciated. Thanks in advance.