java 正确使用 Universal Image Loader

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15703389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:34:26  来源:igfitidea点击:

Correct usage of Universal Image Loader

javaandroidphoto-galleryuniversal-image-loader

提问by Tomislav Turcic

Ok, I've been trying to optimize my photo gallery for days now (this is my first Android project). All photos are loaded via Web page. I've started using Universal Image Loader, but I'm still not content with results.

好的,我几天来一直在尝试优化我的照片库(这是我的第一个 Android 项目)。所有照片都通过网页加载。我已经开始使用 Universal Image Loader,但我仍然对结果不满意。

Here's my class:

这是我的课:

public class Galerija extends Activity {

ArrayList<RSSItem> lista = new ArrayList<RSSItem>();
ArrayList<String> lst_slika = new ArrayList<String>();
RSSItem tempItem = new RSSItem();
ImageAdapter adapter;
ImageLoader imageLoader;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_galerija);

    try 
    {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader myReader = sp.getXMLReader();

        URL url = new URL("http://erdut.gausstesting.info/generateXML/galerija.php");

        XMLHandler myXMLHandler = new XMLHandler();
        myReader.setContentHandler(myXMLHandler);
        myReader.parse(new InputSource(url.openStream()));
        lista = myXMLHandler.getRss_lista();
        lst_slika = lista.get(0).getImages();

    } catch (Exception e) {
        System.out.println(e);
    }

    adapter = new ImageAdapter(this, lst_slika);
    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(adapter);

    gridview.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

        }
    });

} 

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<String> lista;   
    /*
    final ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this.mContext)
    .enableLogging()
    .memoryCacheSize(41943040)
    .discCacheSize(104857600)
    .threadPoolSize(10)
    .build();
    */
    final DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.ic_stub)
    .showImageForEmptyUri(R.drawable.ic_empty)
    .showImageOnFail(R.drawable.ic_error)
    .cacheInMemory()
    .cacheOnDisc()
    .build();

    public ImageAdapter(Context c, ArrayList<String> lista) {
        this.mContext = c;
        this.lista = lista;
        imageLoader = ImageLoader.getInstance();
        //imageLoader.init(config);
        imageLoader.init(ImageLoaderConfiguration.createDefault(c));
    }

    public int getCount() {
        return lista.size();
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;

        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            //ova 3 polja ozna?avaju veli?inu, cropanje i padding prikazanih slika
            imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(0, 0, 0, 0);
        } else {
            imageView = (ImageView) convertView;
        }

        imageLoader.displayImage(lista.get(position), imageView, options);
        //new ImageDownloadTask(imageView).execute(lista.get(position));

        return imageView;
    }
}

}

}

It has definitely sped things up compared to my previous solution, but I'm not content. First of all, I can't even start it on my HTC Incredible S - Just starts an activity with black screen and nothing loads. Why is that?

与我之前的解决方案相比,它确实加快了速度,但我并不满足。首先,我什至无法在我的 HTC Incredible S 上启动它 - 只是在黑屏的情况下启动一个活动,没有任何负载。这是为什么?

It only works on emulator, but it reloads all the images as you scroll. So, once you've scrolled down and then back up, all images appear to be reloaded. Is that how it's suppose to work? Any further ways I can improve this?

它仅适用于模拟器,但会在您滚动时重新加载所有图像。因此,一旦您向下滚动然后再向上滚动,所有图像似乎都已重新加载。这就是它的工作方式吗?我还有什么其他方法可以改进吗?

Thanks in advance!

提前致谢!

回答by Raghunandan

You should consider using asynctask to get urls from the server.

您应该考虑使用 asynctask 从服务器获取 url。

You use should be using a view holder for smooth scrolling and performance. http://www.youtube.com/watch?v=wDBM6wVEO70. The talk is about view holder and listview performance.

您应该使用视图持有者来实现平滑滚动和性能。 http://www.youtube.com/watch?v=wDBM6wVEO70。讨论的是视图持有者和列表视图性能。

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

https://github.com/nostra13/Android-Universal-Image-Loader. Check the topic under Configuration and Display Options.

https://github.com/nostra13/Android-Universal-Image-Loader。检查配置和显示选项下的主题

Instead of downloading it again you should cache images in phone memory or sdcard.

您应该将图像缓存在手机内存或 SD 卡中,而不是再次下载。

It caches images in say sdcard (if you have configured properly) using url as the key. If present display from cache else download, cache and display images.

它使用 url 作为键将图像缓存在 sdcard 中(如果您已正确配置)。如果存在显示从缓存否则下载,缓存和显示图像。

In your custom adapter constructor

在您的自定义适配器构造函数中

 File cacheDir = StorageUtils.getOwnCacheDirectory(activity context, "your folder");//for caching

 // Get singletone instance of ImageLoader
 imageLoader = ImageLoader.getInstance();
 // Create configuration for ImageLoader (all options are optional)
 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
 // You can pass your own memory cache implementation
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnLoading(R.drawable.default_pic)//display stub image until image is loaded
.displayer(new RoundedBitmapDisplayer(20))
.build();

In your getView()

在你的 getView()

viewholder.image=(ImageView)vi.findViewById(R.id.imageview); 
imageLoader.displayImage(imageurl, viewholder.image,options);//provide imageurl, imageview and options.