0

Considering I have a navigation view and few fragments associated with it. I wanted to end the fragment when transited to another

For example if Im in fragment A and I click fragment B (or any), The fragment A should get closed or destroyed.

Note: fragmentTransaction.replace(R.id.container, fragment); doesn't work

code for transaction

if(fragment!=null){
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction ft = fragmentManager.beginTransaction();
            ft.replace(R.id.fl, fragment);
            ft.commit();

        }
  • Possible duplicate of [Remove old Fragment from fragment manager](https://stackoverflow.com/questions/22474584/remove-old-fragment-from-fragment-manager). You should also ensure you are calling `commit()` on your transaction. – Chris Stillwell Nov 07 '18 at 18:07
  • @ChrisStillwell they are using replace which isn't working, consider me playing a video in the 1st fragment and when I switch to 2nd the sound still plays in the background. And yes I have added commit() – Kàrthîk ßàlàkrìshña Nov 07 '18 at 18:13
  • Ah I see now. Are you using VideoView? If so, call `stopPlayback();` in your Fragment's `onPause()` or `onStop()` callback. – Chris Stillwell Nov 07 '18 at 18:19
  • 1
    @ChrisStillwell hmm no. I'm using webview in which there is YouTube video – Kàrthîk ßàlàkrìshña Nov 07 '18 at 18:20

2 Answers2

0

Based on the comments, you're WebView isn't getting unloaded when your Fragment transitions. To resolve this, call webView.stopLoading(); and webView.destroy(); from either the Fragment's onPause() or onStop() callback. you may also want to wrap both of those calls in a null check just in case webView actually does unload. So your code block will look something like this:

if(webView != null){
    webView.stopLoading();
    webView.destroy();
}
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
0

that's easy and handling automatically from android side , just enough after to replace your fragment don't do .addToBackStack(null) and when you go to next fragment , last fragment gone