I have a very simple app that consists of three Fragments and a Bottom Navigation bar, created by using "New Project -> Bottom Navigation Activity" in Android Studio. The first Fragment holds a button, which should take me to the second Fragment, like if the middle button of the Bottom Navigation bar was clicked.
Is there a "standard" way to do this?
I have tried:
launch(...)
of the Navigation component, which seems to launch the Fragment with its own back stack and breaks the bottom navigation.setSelectedItemId(...)
in different ways, which either results in an exception or breaks bottom navigation in different ways.In this post, someone asks the exact same question, but it is marked as a duplicate. I fail to find the answer, especially concerning Navigation component.
Clicking the Button
should have the same effect as if the user taps the corresponding item in the bottom navigation. So you need to call setSelectedItemId() on the BottomNavigationView
. This can only be done in the Activity
displaying the BottomNavigationView
.
One option is to introduce a shared ViewModel
with
LiveData
to be observed by the Activity
onButtonClicked()
to be called by the OnClickListener
of your Button
which will update the LiveData
Once the LiveData
observer fires, your Activity
can call
binding.navView.selectedItemId = R.id.navigation_dashboard
Please note that for passing information about events like this one should choose some data type which can be invalidated after use. See for example LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case)