androidbottomnavigationviewandroid-architecture-navigationandroid-bottomnav

Switch tab on button click with Bottom Navigation and Navigation component


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.

Fragment with Button

Is there a "standard" way to do this?

I have tried:

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.


Solution

  • 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

    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)