Home > Blockchain >  Switch tab on button click with Bottom Navigation and Navigation component
Switch tab on button click with Bottom Navigation and Navigation component

Time:03-02

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:

  • using launch(...) of the Navigation component, which seems to launch the Fragment with its own back stack and breaks the bottom navigation.
  • using 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.

CodePudding user response:

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

  • a LiveData to be observed by the Activity
  • a function 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)

CodePudding user response:

Paste this code from where you want to go to the second fragment

Fragment fragment = new DashboardFragment();
            FragmentManager fm = getActivity().getSupportFragmentManager();
            fm.beginTransaction().replace(R.id.frame_layout, fragment).commit();

For more information click here

  • Related