「android学習」JavaでFragmentを利用するサンプルコード
Javaコード:
private LruCache mMemoryCache;
@Override
protected void onCreate(Bundle savedInstanceState) {
…
RetainFragment mRetainFragment =
RetainFragment.findOrCreateRetainFragment(getFragmentManager());
mMemoryCache = RetainFragment.mRetainedCache;
if (mMemoryCache == null) {
mMemoryCache = new LruCache(cacheSize) {
… // Initialize cache here as usual
}
mRetainFragment.mRetainedCache = mMemoryCache;
}
…
}
class RetainFragment extends Fragment {
private static final String TAG = “RetainFragment";
public LruCache mRetainedCache;
public RetainFragment() {}
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new RetainFragment();
}
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}