Sto definendo un ID per il mio frammento nel layout xml:findFragmentById restituisce sempre null
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_fragment"
...
poi aggiungo questo frammento di metodo onCreate della propria attività:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();
Questo è tutto lavoro bene. Sostituire i frammenti e funziona anche.
tardi sto cercando di recuperare il frammento dal suo ID in uno dei metodi della propria attività:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
In questo modo porta a myFragment essere null
. Sempre.
Quando provo a fare lo stesso con i tag al posto di ID posso recuperare il frammento dal suo tag senza problemi:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();
...
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");
Perché non è possibile findFragmentById trova il frammento, ma findFragmentByTag lo fa? Mi sto perdendo qualcosa?
Provare '(MyFragment) getFragmentManager(). FindFragmentById (R.id.container);' – offset