1

I have a fragment in which there is a nested fragment which I add in this way:

            if (home == null) {
                home = new MyFragment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                transaction.addToBackStack(MyFragment.class.getName());
                transaction.add(R.id.child_fragment, home).commit();
            }

When I enter another fragment and go back the child fragment from above is not there. I checked and the instance is different from null.

UPDATE: I changed the code as suggested by Ashwin S Ashok but it's still not working.

charbinary
  • 1,875
  • 4
  • 17
  • 25

2 Answers2

0

Try using these methods:

// Use this if you don't want to retain the fragment.

protected void replaceFragmentStack(int container, Fragment fragment) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(container, fragment);
    fragmentTransaction.commit();
}

// Use this if you want to add the fragments in a stack.

protected void addFragmentStack(int container, Fragment fragment, String tag) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    fragmentTransaction.add(container, fragment, tag);
    fragmentTransaction.addToBackStack(tag);
    fragmentTransaction.commit();
}
Ashwin S Ashok
  • 3,623
  • 2
  • 29
  • 36
  • I tried with your suggestion but it's not working again. My other fragments work properly but not with the nested fragment. – charbinary Nov 15 '16 at 08:49
0

I would suggest you to use getChildFragmentManager() when making transactions inside a fragment. And its a bug i guess. You can check out this thread it will help you alot Android 4.2: back stack behaviour with nested fragments

Also you need to go through The Curious Techizen's blog

Here is the link for the github project sample for same mechanism

I hope this will help you.

Community
  • 1
  • 1
Zeeshan Shabbir
  • 6,704
  • 4
  • 38
  • 74
  • Thank you very much for the info. But I really would like to do it without the support library because I should make a lot of changes to the fragments. – charbinary Nov 15 '16 at 09:22