構成の変更全体でビットマップをキャッシュするために、ほぼ行ごとにGoogleの例を使用しています。
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#config-changes
フィールドが更新されたときに addBitmapToMemoryCache を呼び出しています。これは、構成の変更 (デバイスのローテーション) の前です。ただし、findOrCreateRetainFragment にデバッグ情報を入れた後:
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new RetainFragment();
Log.w("myapp", "instanciating new retainfragment");
fm.beginTransaction().add(fragment, TAG).commit();
} else {
Log.w("myapp", "using old retainfragment");
}
return fragment;
}
フラグメントは常に新しくインスタンス化されるため、古い LruCache にアクセスすることはありませんsetRetainInstance(true)
。Googleの例に何か問題がありますか? v4 サポート FragmentManager を使用しています。
私のonCreateの関連部分は次のとおりです。
RetainFragment retainFragment =
RetainFragment.findOrCreateRetainFragment(getSupportFragmentManager());
mMemoryCache = retainFragment.mRetainedCache;
if (mMemoryCache == null) {
mMemoryCache = new LruCache<String, Bitmap>(3 * 1024 * 1024) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
retainFragment.mRetainedCache = mMemoryCache;
} else {
backgroundsByMonth = new ArrayList<>();
for (int i = 0; i < 12; i++) {
BitmapDrawable bd = new BitmapDrawable(getResources(), mMemoryCache.get(Integer.toString(i)));
backgroundsByMonth.add(bd);
}
}