How to destroy Fragment?

AndroidAndroid Fragments

Android Problem Overview


I have one Activity. The Activity has two Fragments. Fragment A is Menu. Fragment B is Detail.

I try to Make other Fragment C in Fragment B, so, There are 3 Fragment in the Activity. And I try to Replace Fragment B to Fragment D.

I guess Fragment B and C is dead. BUT these Fragments is alive. Just Fragments are onDestroyView() state. I want onDestroy() or onDetach().

What do I do for Fragments.onDestroy() or onDetach()? I can't destroy or change the Activity.

Android Solutions


Solution 1 - Android

If you don't remove manually these fragments, they are still attached to the activity. Your activity is not destroyed so these fragments are too. To remove (so destroy) these fragments, you can call:

fragmentTransaction.remove(yourfragment).commit()

Hope it helps to you

Solution 2 - Android

Give a try to this

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // TODO Auto-generated method stub

    FragmentManager manager = ((Fragment) object).getFragmentManager();
    FragmentTransaction trans = manager.beginTransaction();
    trans.remove((Fragment) object);
    trans.commit();

    super.destroyItem(container, position, object);
}

Solution 3 - Android

If you are in the fragment itself, you need to call this. Your fragment needs to be the fragment that is being called. Enter code:

getFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();

or if you are using supportLib, then you need to call:

getSupportFragmentManager().beginTransaction().remove(yourFragment).commitAllowingStateLoss();

Solution 4 - Android

> Use this if you're in the fragment.

@Override
        public void onDestroy() {
            super.onDestroy();
    
            getFragmentManager().beginTransaction().remove((Fragment) youfragmentname).commitAllowingStateLoss();
    
        }

Solution 5 - Android

In kotlin we can do this anywhere in our Fragment

 activity?.run {
     supportFragmentManager.beginTransaction().remove(this@MyFragment)
        .commitAllowingStateLoss()  
   }

Solution 6 - Android

It's used in Kotlin

appCompatActivity?.getSupportFragmentManager()?.popBackStack()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIgnitionView Question on Stackoverflow
Solution 1 - AndroidNhat Nam NGUYENView Answer on Stackoverflow
Solution 2 - AndroidManoj MMView Answer on Stackoverflow
Solution 3 - AndroidFarruh HabibullaevView Answer on Stackoverflow
Solution 4 - AndroidOğuzhan GÜMÜŞView Answer on Stackoverflow
Solution 5 - AndroidAllanRibasView Answer on Stackoverflow
Solution 6 - AndroideagerprinceView Answer on Stackoverflow