3

I'm using multiple fragments inside an activity like this flow: Fragment A has a list on it's item click Fragment B opens and it also has a list opens Fragment C which has a list Open another Activity , The problem is when I go back from the other Activity I found Fragment A is opened, How I restore the last Fragment C when go back from the other activity?

here is the code of replacing Fragment inside my activity

 protected void showFragment(Fragment fragment) {

    String TAG = fragment.getClass().getSimpleName();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.container_home, fragment, TAG);
    fragmentTransaction.addToBackStack(TAG);
    fragmentTransaction.commit();
}

2 Answers2

1

replace removes the existing fragment and adds a new fragment. This means when you press back button the fragment that got replaced will be created with its onCreateView being invoked. Whereas add retains the existing fragments and adds a new fragment that means existing fragment will be active.

Use add instead of replace

fragmentTransaction.add(R.id.container_home, fragment, TAG);

I had the same issue solved using the above code.

SHALIN PATEL
  • 126
  • 3
  • 10
0

You can use

 fragmentTransaction.addToBackStack(null);

instead of,

 fragmentTransaction.addToBackStack(TAG);

Hope Your problem will solve.