我制作了一个从网址加载图片的网格视图。它工作得很好,但速度很慢。我认为这会让用户感到烦恼。
在我的代码中,我在GridView适配器中使用Bitmap。这是我的代码
using System;
using Android.Widget;
using Android.App;
using System.Collections.Generic;
using Android.Views;
using Android.Graphics;
using System.Net;
namespace AMUSEAndroid
{
public class GridViewAdapter : BaseAdapter<ImageItem>
{
Activity context;
List<ImageItem> items;
public GridViewAdapter (Activity context, List<ImageItem> gridViewtems)
{
this.context = context;
this.items = gridViewtems;
}
public override int Count {
get { return items.Count; }
}
public override ImageItem this[int position]
{
get { return items[position]; }
}
public override long GetItemId (int position)
{
return position;
}
public override View GetView (int position, View convertView, ViewGroup parent)
{
View view = convertView;
var item = items[position];
if (view == null)
view = context.LayoutInflater.Inflate(Resource.Layout.player_grid_item, null);
ImageView imgIcon = view.FindViewById<ImageView> (Resource.Id.img_play_bg);//.SetImageBitmap (gridViewtems[position]);
view.FindViewById<TextView> (Resource.Id.music_text).Text = item.Heading;
var imageBitmap = GetImageBitmapFromUrl(item.ImageResourceId);
imgIcon.SetImageBitmap(imageBitmap);
return view;
}
public Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
}
}
这里ImageItem是一个Model类。
还有其他方法可以从Gridview中的url加载图像。它可以非常快速地加载图像并使应用程序更快。
提前致谢。
答案 0 :(得分:0)
您需要asynchronous image loading。此任务的当前最新技术由Square's Picasso表示。
我从未在Xamarin中编码,但快速搜索显示我有一个module for Xamarin Picasso。
答案 1 :(得分:0)
我用这个:
private async Task<Bitmap> GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = await webClient.DownloadDataTaskAsync(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
但我使用字典缓存所有图像:
private static Dictionary<string, Bitmap> autoCompleteImages = new Dictionary<string, Bitmap>();
在GetView方法中,我使用&#34; holderView&#34;这段代码从字典中获取缓存的图像:
if (autoCompleteImages.ContainsKey(this.autocompleteSearches[position].PicUrl))
{
holder.imageView.SetImageBitmap(autoCompleteImages[this.autocompleteSearches[position].PicUrl]);
}
else
{
this.UpdateImage(holder, position);
}
这里是UpdateImage方法:
private async void UpdateImage(ViewHolderAutoComplete holder, int position)
{
autoCompleteImages[this.autocompleteSearches[position].PicUrl] = await GetImageBitmapFromUrl(this.autocompleteSearches[position].PicUrl);
holder.imageView.SetImageBitmap(autoCompleteImages[this.autocompleteSearches[position].PicUrl]);
}