1

I'm trying to show Material Bottom Navigation Inside Fragment. My Bottom Navigation View has three fragments inside it. I solve the problem when the Fragment creates a new instance every time when we select the Navigation item. But the real problem occurs when I navigate to another fragment from my Navigation Drawer. Here's how my Bottom Navigation structure looks like.

Main Fragment (All the following items are the bottom navigation view items inside Main Fragment)

  1. Home Fragment

  2. Notification Fragment

  3. Search Fragment

    Here's how I'm adding, showing, and removing fragment with Fragment Manager. It is an extension function.

fun FragmentManager.hideAndShowFragment(
    newFragment: Fragment, containerId: Int, hideFragmentInstance: Fragment? = null
) {
    beginTransaction().apply {
        if (hideFragmentInstance == null) {
            add(containerId, newFragment)
            commit()
            return
        }

        if (fragments.contains(hideFragmentInstance))
            hide(hideFragmentInstance)
        if (fragments.contains(newFragment))
            show(newFragment)
        else add(containerId, newFragment)
        commit()
    }
}

In the above code, the first condition is for when there is no fragment showing and don't need to hide the previous fragment. And then if the FragmentManager List<Fragment> contains the previous fragment first hide, then show the new fragment accordingly.

And this how I'm calling this extension function.

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) : View {
      /////  other stuff
      bottomNav.setOnNavigationItemSelectedListener { menuItem ->
             val previousFragment = getCurrentShowingFragment(currentId)
             val newFragment = getNewFragment(menuItem.itemId)
             childFragmentManager.hideAndShowFragment(newFragment, CONTAINER_ID, previousFragment)
             currentId = menuItem.itemId
      }

      // First time 
      childFragmentManager.hideAndShowFragment(getNewFragment(currentId), CONTAINER_ID, null)
}

Now when I try to navigate to another fragment with Navigation Drawer and came back by pressing back button the current showing fragment view sticks to the screen even I try to click on other bottom nav items it just never disappears.

Here is the video demonstration.

Thanks for your time.

Community
  • 1
  • 1
Ahsan Saeed
  • 701
  • 10
  • 22

0 Answers0