您好 Android 开发人员,我遵循Android开发人员的显示图像指南,RetainFragment
如果我旋转我的设备,我想从 a 加载我的初始化缓存。在我的ListFragments
onActivityCreated()
方法中执行此操作,但片段每次都是新创建的而不是重用。
我做这样的事情: RetainFragment
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);
}
}
和这个:ListFragment
@Override
public void onActivityCreated( Bundle savedInstanceState )
{
super.onActivityCreated( savedInstanceState );
RetainFragment mRetainFragment = RetainFragment.findOrCreateRetainFragment(getFragmentManager());
LruCache mMemoryCache = RetainFragment.mRetainedCache;
if (mMemoryCache == null)
{
mMemoryCache = new LruCache(cacheSize);
mRetainFragment.mRetainedCache = mMemoryCache;
}
else
{
mMemoryCache = mRetainFragment.mRetainedCache;
}
...
}