【发布时间】:2015-11-03 14:59:34
【问题描述】:
我的应用程序中的第一个活动有三个选项卡第一个选项卡包括包含图像列表的回收视图,这些图像来自 web 服务,当单击第二或第三个选项卡,然后单击从 Web 服务加载的第一个选项卡图像再次我想要为片段保存实例
【问题讨论】:
标签: android android-fragments tabs
我的应用程序中的第一个活动有三个选项卡第一个选项卡包括包含图像列表的回收视图,这些图像来自 web 服务,当单击第二或第三个选项卡,然后单击从 Web 服务加载的第一个选项卡图像再次我想要为片段保存实例
【问题讨论】:
标签: android android-fragments tabs
首先,在您的回收器视图的适配器中使用Picasso 库来显示图像。它具有开箱即用的图像缓存。当您第一次下载图像时,它将被缓存在您的设备上。当您再次尝试下载具有相同 URL 的图像时(当您从第三个选项卡返回时)Picasso 将显示缓存中的图像并且不会再次下载。
其次,您可以将图像列表保存在片段中。在您的片段覆盖中
String BUNDLE_IMAGES = "imgs";
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
ourState.putStringArrayList(BUNDLE_IMAGES , getImageArray())
}
private List<String> getImageArray(){
//your implementation to get image array
}
恢复
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
List<String> images =savedInstanceState.getStringArrayList(BUNDLE_IMAGES);
}
}
有关保存/恢复片段状态的更多信息:Once for all, how to correctly save instance state of Fragments in back stack?
更新:使用custom 图像缓存:
private LruCache<String, Bitmap> mMemoryCache;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
...
}
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
【讨论】: