Remove all fragments from container

前端 未结 9 1700
死守一世寂寞
死守一世寂寞 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:48

    As an addition to useful answers I have to say that if you have added few fragments to specific view container, for example:

    getSupportFragmentManager()
        .beginTransaction()
        .add(containerViewId, fragmentA)
        .add(containerViewId, fragmentB)
        .commit();
    

    and if you need just replace them by one, you can simply call replace without removing fragmentA and fragmentB

    getSupportFragmentManager()
        .beginTransaction()
        .replace(containerViewId, fragment)
        .commit();
    

    According to the docs replace removes all fragments before adding new:

    Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

提交回复
热议问题