ylimit
ylimit

Reputation: 621

How to destroy Fragment?

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.

Upvotes: 62

Views: 140998

Answers (7)

TinaTT2
TinaTT2

Reputation: 489

All you need to do is calling parentFragmentManager.beginTransaction().remove(fragment).commit(). Remember that fragment.onDestroy() won't pop it up from the parentFragmentManager.fragments stack. The complete example code will be:

 parentFragmentManager.fragments.onEach {
                if (it is SpecifiedFragment) {
                   parentFragmentManager.beginTransaction().remove(it).commit()
                }
            }

Upvotes: 0

AllanRibas
AllanRibas

Reputation: 1144

In kotlin we can do this anywhere in our Fragment

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

Upvotes: 1

Use this if you're in the fragment.

@Override
        public void onDestroy() {
            super.onDestroy();

            getFragmentManager().beginTransaction().remove((Fragment) youfragmentname).commitAllowingStateLoss();

        }

Upvotes: 1

Farruh Habibullaev
Farruh Habibullaev

Reputation: 2392

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();

Upvotes: 12

eagerprince
eagerprince

Reputation: 123

It's used in Kotlin

appCompatActivity?.getSupportFragmentManager()?.popBackStack()

Upvotes: -4

Manoj MM
Manoj MM

Reputation: 490

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);
}

Upvotes: 12

Nhat Nam NGUYEN
Nhat Nam NGUYEN

Reputation: 1272

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

Upvotes: 81

Related Questions