findFragmentById renvoie toujours null

Je suis à la définition d'un ID pour mon fragment dans le fichier xml du layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_fragment"
...

Puis-je ajouter ce fragment dans la méthode onCreate:

MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();

C'est tous fonctionne bien. Remplacement de fragments et est également à l'œuvre.

Plus tard, je suis en train de récupérer ce fragment par son ID dans celui de l'activité, méthodes:

MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);

Le faire conduit à myFragment être null. Toujours.

Quand j'essaie de faire la même chose avec des mots au lieu de Id je peux récupérer le fragment de son étiquette sans aucun problème:

MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();

...

MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");

Pourquoi ne peut-findFragmentById trouver le fragment, mais findFragmentByTag fait? Ai-je raté quelque chose?

  • Essayez (MyFragment) getFragmentManager().findFragmentById(R.id.container);
InformationsquelleAutor Viper | 2012-05-31