2

I am working with fragments and the navigation flow like

 Fragment A -> Fragment B -> Fragment C -> Fragment D 

Form fragment D I need to navigate to fragment A by clearing back stack but the problem is in onCreateView() method of fragment C I am showing one dialog

When I am navigating from D to A by clearing the back stack Over fragment A same pop-up appears which was shown in on fragment C

below is the code I am using to clear the stack

FragmentManager fm = getActivity().getSupportFragmentManager();

for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
     fm.popBackStack();
   }
Goku
  • 9,102
  • 8
  • 50
  • 81
user_8275
  • 233
  • 4
  • 15

1 Answers1

2

The problem you have lies in the way you are dealing with the fragments lifecycle. You want Fragment C to do onCreateView only once (to show the popup), but onCreateView get's called every time the View is created (e.g, every time you call remove on a fragment(replace works pretty much the same, remove + add) and then add it back from backstack with popbackstack).

For your problems there are two solutions:

Cleaner one: instead of showing your popup from onCreateView, call it from onCreate in Fragment C. With this you will guarantee that it only get's called when the fragment instance is created.

Not so clean: Instead of using replace between Fragment C and D transaction, call add, this way when you pop the backstack in Fragment D, Fragment C onCreateView won't be called because the View was never destroyed (never called remove/replace upon).

Ricardo
  • 9,136
  • 3
  • 29
  • 35
  • Using add method works fine for me but i didn't get why you said that its not so clean – user_8275 Nov 09 '17 at 17:33
  • I didn't say it wasn't clean, I said it wasn't so clean. To use Fragment replacement gives you a full control of what happens in your container, which does not happen as easily with add. It still a good approach. – Ricardo Nov 09 '17 at 17:39