简体   繁体   中英

Xamarin.Android How do I create a swipeable image gallery using ViewPager?

Android gallery is now deprecated, so I need to use ViewPager. I only found code samples for Xamarin.Forms, so I would appreciate if someone could help me with a code sample for Xamarin.Android.

My question is different from Click on Viewpager Xamarin Android because I don't need to click the photos, I only needed to swipe the images in the gallery.

Although its a different question there is a solution here that doesn't require you to use an image fragment for a simple slider. https://stackoverflow.com/a/33209130/5436000

public class ImageSliderAdapter : PagerAdapter
{
    Context _context;
    List<string> _imageUrls;

    public ImageSliderAdapter (Context context, List<string> imageUrls)
    {
        _imageUrls = imageUrls;
        _context = context;
    }

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

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

    public override void DestroyItem (ViewGroup container, int position, Java.Lang.Object objectValue)
    {
    }

    public override Java.Lang.Object InstantiateItem (ViewGroup container, int position)
    {

        View view = container;
        var inflater = _context.GetSystemService (Context.LayoutInflaterService) as LayoutInflater;
        view = inflater.Inflate (Resource.Layout.image_slider_item, null);
        var child = view.FindViewById<ImageView> (Resource.Id.image_slider_item);
        child.Click += (o, e) =>
        {
            //your code here
        };

        Bitmap image = null;
        Task.Run (() => {
            URL url = new URL (_imageUrls [position]);
            image = BitmapFactory.DecodeStream (url.OpenConnection ().InputStream);
        }).ContinueWith (t => {
            (_context as MainView).RunOnUiThread (() => {
                child.SetImageBitmap (image);
            });
        });

        container.AddView (view);
        return view;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM