Reputation: 5173
I'm trying to set up a navigation component with the bottom navbar. it is being set since I'm getting the fragment that has been set as home as the fragment. However it's not changing on pressing the other buttons.
activity_main.xml
<fragment
android:id="@+id/fragNavHost"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/bottom_nav_graph" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottomNavView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
style="@style/Widget.MaterialComponents.BottomNavigationView"
app:menu="@menu/menu"/>
bottom_nav_graph.xml
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/bottom_nav_graph.xml"
app:startDestination="@id/homeFragment">
<fragment
android:id="@+id/homeFragment"
android:name="com.example.testproject.HomeFragment"
android:label="fragment_home"
tools:layout="@layout/fragment_home" />
<fragment
android:id="@+id/profileFragment"
android:name="com.example.testproject.ProfileFragment"
android:label="fragment_profile"
tools:layout="@layout/fragment_profile" />
<fragment
android:id="@+id/searchFragment"
android:name="com.example.testproject.SearchFragment"
android:label="fragment_search"
tools:layout="@layout/fragment_search" />
</navigation>
and used it in the main activity like so.
// Finding the Navigation Controller
var navController = findNavController(R.id.fragNavHost)
// Setting Navigation Controller with the BottomNavigationView
bottomNavView.setupWithNavController(navController)
What am I doing wrong?
Edit: Solved. the name in my menu was different to the ids
Upvotes: 2
Views: 3437
Reputation: 941
When using navigation controls, you need to use the navigate() method to navigate to the corresponding fragment
like this:
findNavController().navigate(R.id.action_inputNetInfoFragment_to_inputMasterInfoFragment)
Upvotes: 0
Reputation: 634
I execute below code in onCreate to get it working.
val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
bottomNavigation.setupWithNavController(navController)
Upvotes: 4