异步图像下载并在android Xamarin的Gridview中显示,中断Getview中的位置
在主活动中,我创建了一个函数,在路径列表中循环并下载图像异步图像下载并在android Xamarin的Gridview中显示,中断Getview中的位置,android,gridview,bitmap,xamarin,async-await,Android,Gridview,Bitmap,Xamarin,Async Await,在主活动中,我创建了一个函数,在路径列表中循环并下载图像 async void downloadAsync() { foreach (string item in string_List) { if (!File.Exists(Path)) { webClient = new WebClient(); va
async void downloadAsync()
{
foreach (string item in string_List)
{
if (!File.Exists(Path))
{
webClient = new WebClient();
var url = new Uri(item);
byte[] imageBytes = null;
imageBytes = await webClient.DownloadDataTaskAsync(url);
//Save the Image using writeAsync
FileStream fs = new FileStream(Path, FileMode.OpenOrCreate);
await fs.WriteAsync(imageBytes, 0, imageBytes.Length);
//Close file connection
fs.Close();
}
}
}
在get view函数中的网格视图适配器上,输入用于加载imageview的代码
public override View GetView(int position, View view, ViewGroup parent)
{
// retrieve the view
View vw = view;
ImageView picture;
if (vw == null)
{
// code for create the image view
}
if (File.Exists(Path))
{
Bitmap bitmap = null;
bitmap =BitmapFactory.DecodeFile(path);
picture.SetImageBitmap(bitmap);
}
}
当我在网格上滚动以显示图像时,我发现在下载完成之前,图像位于不正确的位置,之后的所有内容都会调整到正确的位置。这是因为您的位图工厂.DecodeFile与视图在同一任务下运行,因此它可能会在“下载”时出错照片 您需要在异步版本的DecodeFile下运行它 请像这样尝试:
bitmap = await BitmapFactory.DecodeFileAsync(path);
picture.SetImageBitmap(bitmap);
谢谢你的帮助,但我仍然有同样的问题,那就是当我想在Gridview上滚动时,它被称为getview(override函数),它是interput并获取位置参数的假值,所以我认为最好的方法是,获取列表中的所有图像。在此之后,循环此列表并逐个添加。我看到了,但正如我告诉您的,从GridView适配器调用的get view函数的参数position返回假值,即当您向下滚动而不是将位置读取为16时,例如,将其返回为零。