dasmikko
dasmikko

Reputation: 706

Xamarin.Android ViewPager with only ImageViews

I'm trying to make a ViewPager containing only ImageView.

But it keeps giving me errors on this line.

((ViewPager)collection).AddView (i);
System.InvalidCastException: Cannot cast from source type to destination type.

Here is my ViewPagerAdapter

public class GalleryAdapter : PagerAdapter
{
    Context context;
    private List<string> mitems;

    public GalleryAdapter (Context c, List<string> items)
    {
        context = c;
        mitems = items;
    }

    public override int Count { get { return mitems.Count; } }

    public override Java.Lang.Object InstantiateItem (View collection, int position)
    {
        ImageView i = new ImageView (context);

        //i.LayoutParameters = new Gallery.LayoutParams (150, 100);
        i.SetScaleType (ImageView.ScaleType.FitCenter);

        Picasso.With (context).Load (mitems [position]).Into (i);
        ((ViewPager)collection).AddView (i);
        return i;
    }

    public override bool IsViewFromObject (View view, Java.Lang.Object @object)
    {
        return view == @object;
    }
}

I have no idea where to continue from this.

Upvotes: 0

Views: 1148

Answers (2)

Ali Haidar
Ali Haidar

Reputation: 11

try the following

public override Java.Lang.Object InstantiateItem (View collection, int position)
{
    ImageView i = new ImageView (context);

    //i.LayoutParameters = new Gallery.LayoutParams (150, 100);
    i.SetScaleType (ImageView.ScaleType.FitCenter);

    Picasso.With (context).Load (mitems [position]).Into (i);
    var viewPager = collection.JavaCast<ViewPager>();

    viewpager.AddView (i);

    return i;
}

Upvotes: 1

Andrew Porritt
Andrew Porritt

Reputation: 1746

Looking through the Android documentation, it looks like the first parameter passed to InstantiateItem is just a view which will contain your content, and not necessarily the ViewPager itself. In fact, the version of InstantiateItem which takes a View parameter is deprecated in favour of one which takes a ViewGroup. I'm not sure if the Xamarin wrapper has this method in it, but in either case, try casting to a ViewGroup instead of a ViewPager:

((ViewGroup)collection).AddView (i);

You might want to rename the 'collection' variable to 'container' too, just to be clear that you're not adding it directly to the ViewPager, rather to a subview which is owned by the ViewPager.

Upvotes: 3

Related Questions