1

Hello Android Developer, i follow the Display Images Guide from Android Developers and want to load my initialized cache from a RetainFragment if i rotate my device. A do this in my ListFragments onActivityCreated() method but the fragment is every time new created and not reused.

I do something like this: 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);
}

}

And this: 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;
    }
    ...
}
4

1 に答える 1

2

It looks to me like they forgot to actually attach that RetainFragment somehow to the Activity so FragmentManager has a chance to find it. Fragments that are not attached don't survive configuration changes.

Not sure if but it should work with the addition below

public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
    RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
    if (fragment == null) {
        fragment = new RetainFragment();
        // add this line
        fm.beginTransaction().add(fragment, TAG).commit();
    }
    return fragment;
}
于 2012-08-14T20:21:17.583 に答える