Search code examples
androidandroid-fragmentsfragmentmanager

Adding Fragment to containers with the same ID


I have a ViewPager to implement swipe between "holder" Fragments. And inside them I need to add multiple Fragments to their respective containers.

The problem is, Im using FragmentTransaction.add(containerID, fragment);, but since there are multiple holder Fragments in the ViewPager, all the Fragments get added on the same holder Fragment, and not in the one that is calling to add them.

Anyone has an idea on a good practice to go around this problem?

Here is the code where I add the Fragments inside the holder fragment.

arrayFragments = new ArrayList<DiaAgendaFragment>();
DiaAgendaFragment objFragment;
FragmentManager fm = getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();

//this will be set accordingly later for each fragment
Time dataFragment = new Time();
dataFragment.setToNow();

//instantiate and set fragments
for (int i = 0; i < 5; i++) {

    objFragment = DiaAgendaFragment.newInstance(5, dataFragment);
    arrayFragments.add(objFragment);
    //pega a View pelo nome e adiciona o fragment
    transaction.add(getActivity().getResources().getIdentifier("agenda5d_activity_fragment"+i, "id", getActivity().getPackageName()), arrayFragments.get(i));
    //codigo de teste
    dataFragment.monthDay += 1;
}
transaction.commit();

Solution

  • You have to use the child FragmentManager if you want to add Fragments to another Fragment. Using the normal FragmentManager will not work as you found out yourself.

    In your Fragment:

    FragmentManager manager = getChildFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    ...
    transaction.commit();