2012-08-14 3 views
1

Bonjour développeur Android, je suis le guide d'affichage des images de Android Developers et je veux charger mon cache initialisé à partir d'un RetainFragment si je fais pivoter mon appareil. A le faire dans ma méthode ListFragmentsonActivityCreated() mais le fragment est à chaque fois nouveau créé et non réutilisé.charger RetainFragment dans un fragment

je fais quelque chose comme ceci: 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); 
} 

}

Et ceci: 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; 
    } 
    ... 
} 

Répondre

2

Il semble à moi comme ils ont oublié de joindre en fait que RetainFragment en quelque sorte au Activity alors FragmentManager a une chance de le trouver. Les fragments qui ne sont pas attachés ne survivent pas aux modifications de configuration.

Je ne sais pas si, mais il devrait fonctionner avec l'ajout ci-dessous

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; 
} 
+0

Ce travail vraiment bon. Merci pour le tipp. – Happo

+0

Grande prise. Dommage que la ligne que vous avez ajoutée ne soit pas incluse dans la [documentation] officielle (http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html). – Ron

Questions connexes