简体   繁体   English

Android将图像加载到ListView AsyncTask

[英]Android loading images to ListView AsyncTask

This is more a question of application logic and performance. 这更多是一个应用逻辑和性能问题。

Project Setup: I have an Android ListView which inflates a layout that is more aesthetically pleasing than just simple text. 项目设置:我有一个Android ListView,它可以使版面夸张,而不仅仅是简单的文本。 In each row (7 to be exact), I have an Image that is fetched by URL. 在每一行中(确切地说是7行),我都有一个通过URL提取的图像。

The problem: This ListView and its data are set by an ArrayList of model objects that serve as temporary data holders. 问题:此ListView及其数据由充当临时数据持有者的模型对象的ArrayList设置。 When the rows are added the model objects are then used to set the data in the specific row's UI. 添加行后,将使用模型对象在特定行的UI中设置数据。 The issue then comes along, that when a user scrolls down on the list a row that was once viewable is now out of the user's view. 随之而来的问题是,当用户在列表上向下滚动时,曾经可见的行现在不在用户的视野之内。 When the user scrolls back up to that row, the whole process of fetching the Image then happens again. 当用户向后滚动到该行时,获取图像的整个过程将再次发生。

This seems like it can be avoided by instead of passing URLs through the models then fetching the images, I should fetch the images first, then pass the bitmaps to the model, therefore when the row is visible again to the user, it does not have to re-load the image. 这似乎可以避免,而不是通过模型传递URL,然后获取图像,我应该首先获取图像,然后将位图传递给模型,因此,当用户再次看到该行时,它就不会重新加载图像。

Is there a way to write an AsyncTask that can load 7 images successfully, or do I have to create an AsyncTask object for each image? 有没有一种方法可以编写可以成功加载7个图像的AsyncTask,还是必须为每个图像创建一个AsyncTask对象?

Everytime I go this route the application crashes... 每当我走这条路线时,应用程序就会崩溃...

You can use Picasso library for this task. 您可以将Picasso库用于此任务。 Visit http://square.github.io/picasso/ 访问http://square.github.io/picasso/

In the adapter of your ListView, in the method getView, you can put this: 在ListView的适配器中,在getView方法中,可以输入以下内容:

     Picasso.with(context) 
     .load(url)
     .placeholder(R.drawable.ic_launcher)
     .error(R.drawable.ic_error) 
     .resizeDimen(R.dimen.list_detail_image_size,R.dimen.list_detail_image_size)                              .centerInside()
    .into(imgView);

You dont need a AsyncTask because this library already implements itself. 您不需要AsyncTask,因为此库已经实现了它自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM