异步图像下载并在 Gridview for android Xamarin 中显示它们会中断 Getview 中的位置



在主活动上,我做了一个函数,在路径列表中循环并下载图像

      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();
                }
          }     
       }

并在网格视图适配器上获取视图功能,输入用于加载图像视图的代码

    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);
        }
    }

当我在网格上滚动以显示图像时,我发现图像位于不正确的位置,直到下载完成,之后的所有内容都会在正确的位置进行调整。

这是因为您的BitmapFactory.DecodeFile在与视图相同的任务下运行,因此在"下载"图片时可能会犯一些错误

您需要使用解码文件的异步版本运行它

请尝试如下:

bitmap = await BitmapFactory.DecodeFileAsync(path);
picture.SetImageBitmap(bitmap);

最新更新