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

前端 未结 1 842
無奈伤痛
無奈伤痛 2021-01-14 14:22

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

相关标签:
1条回答
  • 2021-01-14 14:46

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题