0

如何从 JSON 延迟加载图像以在 Android GridView 中预览?一个完整的例子将不胜感激。

4

3 回答 3

1

我建议使用通用图像加载器来加载图像,并使用 gson库从 JSON 创建对象。

于 2013-05-14T04:43:59.080 回答
0

您可以从 JSON 获取图像 url 并使用 ASyncTask 下载图像。如果需要,您可以将视图传递给 asynctask 并从它的 postexecute 中设置其图像源

于 2013-05-14T04:47:32.707 回答
0

您需要解析您的 json 响应以获取图像的 url。然后使用带有自定义适配器的 grdiview。将 url 传递给自定义适配器构造函数。

解析 json 使用 gson

https://code.google.com/p/google-gson/

相同的教程

http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

您可以使用惰性列表或通用 ImageLoader。

图像可以缓存到本地sd卡或手机内存。Url 被认为是关键。如果密钥存在于 sdcard 中,则显示来自 sd 卡的图像,否则通过从服务器下载显示图像并将其缓存到您选择的位置。可以设置缓存限制。您还可以选择自己的位置来缓存图像。缓存也可以清除。

而不是用户等待下载大图像然后显示惰性列表按需加载图像。由于图像区域缓存,您可以离线显示图像。

https://github.com/thest1/LazyList。懒惰列表

在你的 getview

imageLoader.DisplayImage(imageurl, imageview);
ImageLoader Display method

public void DisplayImage(String url, ImageView imageView) //url and imageview as parameters
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);   //get image from cache using url as key
if(bitmap!=null)         //if image exists
    imageView.setImageBitmap(bitmap);  //dispaly iamge
 else   //downlaod image and dispaly. add to cache.
 {
    queuePhoto(url, imageView);
    imageView.setImageResource(stub_id);
 }

惰性列表的替代方法是通用图像加载器

https://github.com/nostra13/Android-Universal-Image-Loader。它基于惰性列表(工作原理相同)。但它还有很多其他配置。我更喜欢使用Universal Image Loader,因为它为您提供了更多配置选项。如果下载失败,您可以显示错误图像。可以显示带圆角的图像。可以缓存在磁盘或内存上。可以压缩图像。

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

 File cacheDir = StorageUtils.getOwnCacheDirectory(a, "your folder");

// 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()
.showStubImage(R.drawable.stub_id)//display stub image
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();

在你的 getView()

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

您可以配置其他选项以满足您的需求。

与延迟加载/通用图像加载器一起,您可以查看持有者以实现平滑滚动和性能。http://developer.android.com/training/improving-layouts/smooth-scrolling.html

于 2013-05-14T05:03:28.793 回答