【问题标题】:Load images in listview only when they are about to display仅当它们即将显示时才在列表视图中加载图像
【发布时间】:2023-03-28 12:01:01
【问题描述】:

我正在制作一个音乐播放器,到目前为止我所做的是我在列表视图中创建了一个歌曲列表,其中包含使用元数据文件的缩略图。 现在,当我滚动列表时它会滞后,这可能是因为图像加载。 我提到了谷歌播放音乐应用程序,他们所做的是他们在滚动时获取专辑封面,因此滚动很流畅。 有没有办法实现这种功能?

【问题讨论】:

标签: android listview android-activity scroll metadata


【解决方案1】:

您必须使用延迟加载图像,因此图像将在后台下载。

public class DownloadImage extends AsyncTask<ImageView, Void, Bitmap> {

    ImageView imageView = null;

    @Override
    protected Bitmap doInBackground(ImageView... imageViews) {
        this.imageView = imageViews[0];
        return download_Image((String) imageView.getTag());
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }

    private Bitmap download_Image(String url) {
        try {
            URL ulrn = new URL(url);
            HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();

            InputStream iS = con.getInputStream();
            Bitmap bmp = BitmapFactory.decodeStream(iS);
            return bmp;

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

}

在你的适配器 getview 中调用这个类

imgThumbnail.setTag(<your image url>);
new DownloadImage().execute(imgThumbnail);

【讨论】:

  • 我不想从 url 获取图像。我要他们从uri。方法是什么? imgThumbnail 是 ImageView 吗?
  • 这是异步任务,imgthumbnail 是一个图像视图。您可以修改异步任务以满足您的要求。如果您需要示例,请给我一个示例 uri
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 1970-01-01
相关资源
最近更新 更多