I have a bottom navigation menu with 3 items: Home, Favorites, and Settings. I'm using Fragment container:
<FrameLayout android:id="@+id/fragment_container" />
<com.google.android.material.bottomnavigation.BottomNavigationView app:menu="@menu/bottom_navigation_menu" />
In the BaseFragment, where I want to actually navigate I'm using setOnNavigationItemSelectedListener
where I override the onNavigationItemSelected(item: MenuItem)
function
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
childFragmentManager.beginTransaction().replace(R.id.fragment_container, BeerListFragment())
.commit()
val bottomNavigationView: BottomNavigationView? = view?.findViewById(R.id.bottom_navigation)
bottomNavigationView?.setOnNavigationItemSelectedListener(object :
BottomNavigationView.OnNavigationItemSelectedListener {
override fun onNavigationItemSelected(item: MenuItem): Boolean {
var activeFragment: Fragment = BeerListFragment()
when (item.itemId) {
R.id.nav_home -> let {
activeFragment = BeerListFragment()
return true
}
// similiar for the other two options
}
childFragmentManager.beginTransaction()
.replace(R.id.fragment_container, activeFragment).commit()
return true
}
})
The problem seems to be that the ids of the layouts for the fragments are not checked in when()
statement. If I pass different from BeerListFragment()
in the first line of the onCreate()
function, it works, so I think there should be an issue with the setOnNavigationItemSelectedListener
.
Is there any other way that I can navigate to the particular fragment? I've tried using actions in the navigation_graph, but I don't think it's necessary because I have a bottom navigation menu.
if you're using navigation component why do you use childFragmentManager.beginTransaction().replace(R.id.fragment_container, BeerListFragment()).commit()
?
If you use navigation component and you want your BottomNavigationView
item to redirect to your fragment
you don't need any code except giving the right ids in the item of your BottomNavigationView
menu.
Here is a quick tutorial to help you.