Remove all fragments from container

前端 未结 9 1575
死守一世寂寞
死守一世寂寞 2021-02-01 00:56

Is there a way to remove all fragments which already added the specific view with its view id?

For example I want to remove all fragments which is added R.id.fragmentcon

相关标签:
9条回答
  • 2021-02-01 01:25

    Use this code

    activity?.let {
    it.supportFragmentManager.fragments.forEach { fragment ->
            it.supportFragmentManager.beginTransaction().remove(fragment).commit()
        }
    }
    

    Hope it helps.

    Thank you.

    0 讨论(0)
  • 2021-02-01 01:31

    In case someone is looking for a code in Kotlin:

    private fun clearFragmentsFromContainer() {
                val fragments = supportFragmentManager.fragments
                if (fragments != null) {
                    for (fragment in fragments) {
                        supportFragmentManager.beginTransaction().remove(fragment).commit()
                    }
                }
                //Remove all the previous fragments in back stack
                supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
    }
    
    0 讨论(0)
  • 2021-02-01 01:32

    More optimized version
    There is no need in multiple call of commit so lets call it one time at the end

    supportFragmentManager.fragments.let {
        if (it.isNotEmpty()) {
            supportFragmentManager.beginTransaction().apply {
                for (fragment in it) {
                    remove(fragment)
                }
                commit()
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-01 01:32

    Try this, hope it helps :D

    try {
    if(manager.getFragments()!=null){
        if(manager.getBackStackEntryCount()>0) {
            for (int i = 0; i < manager.getBackStackEntryCount(); i++)
                manager.popBackStack();
    
            manager.beginTransaction().remove(getSupportFragmentManager()
            .findFragmentById(R.id.main_content))
            .commit();
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    } 
    
    0 讨论(0)
  • 2021-02-01 01:34

    It is indeed very simple.

    private static void removeAllFragments(FragmentManager fragmentManager) {
        while (fragmentManager.getBackStackEntryCount() > 0) {
            fragmentManager.popBackStackImmediate();
        }
    }
    
    0 讨论(0)
  • 2021-02-01 01:36

    You can try below code

    getSupportFragmentManager().beginTransaction().remove(frag).commit(); 
    

    *frag is the object of fragment that you want to remove.

     OR
    getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentById(R.id.your_container)).commit();
    

    it will remove the fragment that is loded in "your_container" container.

    HapPy coding.

    0 讨论(0)
提交回复
热议问题