Add (not replace) fragment with navigation architecture component

后端 未结 6 1888
失恋的感觉
失恋的感觉 2021-01-31 02:14

I have an activity with a product list fragment and many other fragments and I am trying to use architecture component navigation controller.

The problem is: it replaces

6条回答
  •  花落未央
    2021-01-31 02:26

    You have to override NavHostFragment's createFragmentNavigator method and return YourFragmentNavigator.

    YourFragmentNavigator must override FragmentNavigator's navigate method.

    Copy and paste FragmentNavigator's navigate method to your YourFragmentNavigator.

    In navigate method, change the line ft.replace(mContainerId, frag); with

    if (fragmentManager.fragments.size <= 0) {
        ft.replace(containerId, frag)
    } else {
        ft.hide(fragmentManager.fragments[fragmentManager.fragments.size - 1])
        ft.add(containerId, frag)
    }
    

    The solution will look like this:

    class YourNavHostFragment : NavHostFragment() {
    override fun createFragmentNavigator(): Navigator<...> {
        return YourFragmentNavigator(...)
    }}
    

    ....

    class YourFragmentNavigator(...) : FragmentNavigator(...) {
    
    override fun navigate(...){
        ....
        if (fragmentManager.fragments.size <= 0) {
            ft.replace(containerId, frag)
        } else {
            ft.hide(fragmentManager.fragments[fragmentManager.fragments.size - 1])
            ft.add(containerId, frag)
         }
         ....
    }}
    

    in your xml use YourNavHostFragment.

提交回复
热议问题