I define the ID for my fragment in the xml layout:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/test_fragment" ...
Then I add this snippet to the onCreate action:
MyFragment myFragment = new MyFragment(); fragmentTransaction.add(R.id.fragment_container, myFragment); fragmentTransaction.commit();
Everything is working fine. Replacing fragments also works.
Later, I try to extract this fragment by its identifier in one of the activity methods:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
This causes myFragment to be null . Always.
When I try to do the same with tags instead of IDs, I can easily get a snippet by tag:
MyFragment myFragment = new MyFragment(); fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment"); fragmentTransaction.commit();
...
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");
Why can't findFragmentById find the fragment, but findFragmentByTag does this? Did I miss something?
android android-fragments
Viper May 31 '12 at 12:31 2012-05-31 12:31
source share