2015-09-13 1 views
0

J'ai un Activity dans lequel je change le contenu en remplaçant un Fragment. Dans le onCreate de cette Activity, je mets le premier Fragment avec ce code:FragmentManager.findFragmentByTag renvoie toujours la valeur null

fm.beginTransaction().add(R.id.container, new FooFragment(), "f_0").commit(); 

Après cela, je veux changer cette Fragment par un autre en fonction d'une Integer (j'utiliser un tiroir), voici le Code:

int position = //I get my index here 
Fragment f = fm.findFragmentByTag("f_" + position); //(1) 

if (f == null) { 
    switch (position) { 
     case 0: 
      f = new FooFragment(); 
      break; 
     case 1: 
      f = new BarFragment(); 
      break; 
     //Etc... 
    } 
} 

//Then I replace the actual Fragment by the new one 
fm.beginTransaction() 
    .replace(R.id.container, f, "f_" + position) 
    .commit(); 

Mon problème est que le code sur (1) null retour toujours si chaque fois que je change le Fragment, il crée une nouvelle instance. Je veux avoir à tout moment une seule instance de chaque type Fragment.

Merci.

Répondre

0

Set premier fragment:

getSupportFragmentManager().beginTransaction().addToBackStack("f_0").replace(R.id.container, new FooFragment(), "CURRENT_FRAGMENT_TAG").commit(); 


Cette fonction permet de fragments remplacent:

public void replaceFragment(Fragment fragment, String tag) { 
    Fragment currentFragment = getSupportFragmentManager().findFragmentByTag("CURRENT_FRAGMENT_TAG"); 

    //to avoid adding the same fragment, you can use 'instanceof' instead of comparator 
    if (currentFragment.getClass() == fragment.getClass()) { 
     return; 
    } 
    getSupportFragmentManager().popBackStack(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE); 
    getSupportFragmentManager() 
      .beginTransaction() 
      .addToBackStack(tag).replace(R.id.container, fragment, "CURRENT_FRAGMENT_TAG") 
      .commit(); 

} 

Exemple exécution:

replaceFragment(new FooFragment(), "f_" + position); 


Remplacer onBackPressed.

@Override 
public void onBackPressed() { 
    if (getSupportFragmentManager().getBackStackEntryCount() == 1) { 
     finish(); 
    } else { 
     super.onBackPressed(); 
    } 
} 
+0

obtenu le même numéro:/ Je l'ai testé avec un 'int' statique pour compter le nombre d'instance de la' FooFragment' et augmentent encore chaque 'Fragment'swap. – Chaniro

+0

Donc si vous voulez vraiment une instance de fragment ('onCreate' ne sera appelée qu'une fois), vous ne devriez pas utiliser mu solution, et dans vos fragments, dans la méthode' onCreate' ajouter 'setRetainInstance (true)'. –