【问题标题】:How to load image from Url in Recycler view如何在 Recycler 视图中从 Url 加载图像
【发布时间】:2015-10-29 06:43:13
【问题描述】:

我是 android 新手,我想知道如何在 Recycler 视图中从 URL 加载图像,以及在从 URL 加载图像时轻松定义 Bitmap 的用途及其功能。我不想使用任何第三方库。请为此提供解决方案。

【问题讨论】:

标签: java android


【解决方案1】:

您的问题似乎有点不清楚您是否要求阅读带有 URL 或其他任何内容的图像。如果是这样,您可以像这样读取图像并将其设置为您的ImageView

InputStream in = (InputStream) new URL(imageUrl).getContent(); //Reads whatever content found with the given URL Asynchronously And returns.
                Bitmap bitmap = BitmapFactory.decodeStream(in); //Decodes the stream returned from getContent and converts It into a Bitmap Format
                yourImageView.setBitmap(bitmap); //Sets the Bitmap to ImageView
                in.close(); //Closes the InputStream

imageUrl 是一个完整的 URL,它指向您的图片,例如 something.com/image1.jpg

【讨论】:

  • 是的,首先是阅读,然后我想在 Recycler 视图中显示多个 Url 图像。你能解释一下Bitmap的概念吗?
  • 好的,我已经添加了一些 cmets 用于代码清除。 Bitmap 是一个类,表示图像和 Drawable 的特定类型。您可以查看 Bitmap Doc 了解详细信息。 developer.android.com/reference/android/graphics/Bitmap.html
  • 能否提供一个示例程序,以便我更准确地理解?
  • 自己创建一个应用程序。在 xml 中放置一个 ImageView。并复制我给出的代码并粘贴。将 imageUrl 替换为此示例的 URL gstatic.com/webp/gallery3/1.png 您的 ImageView 将显示来自 URL 的图像。 注意:yourImageView 的意思是你的 imageview。并且不要忘记在 url 前加上 https://
【解决方案2】:

我想你已经有了字符串 URL。参考这个链接bitmap link here 这个方法可以在 onBindViewHolder() 中声明。

【讨论】:

  • 真的很有帮助
【解决方案3】:

正如他们所说,您应该使用第三方库。 你可以在这里选择它们https://android-arsenal.com/

我会推荐 Glide:http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en

【讨论】:

    【解决方案4】:

    我找到了问题的答案,我使用 Asynctask 加载多个 URL 以从 url 加载图像,而不使用第三方库。下载发生在后台线程中。这减少了主 UI 线程上的工作,并且下载在后台线程上并行运行,位图的结果被传递给 onPostExecute() 方法。最终可以传递给 OnBindViewHolder 以将图像绑定到其各自的视图。

    【讨论】: