Alin
Alin

Reputation: 14581

Android Jetpack Navigation component and BottomAppBar menu interaction

I am trying to implement Navigation inside my project while having Top App Bar and Bottom App Bar in my main activity.

Here are the steps I've made.

In my activity layout

<android.support.design.widget.CoordinatorLayout>
       <android.support.design.widget.AppBarLayout>
           <android.support.v7.widget.Toolbar/>
       </android.support.design.widget.AppBarLayout>

  <fragment
        android:id="@+id/navigation_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation_graph" />

<android.support.design.bottomappbar.BottomAppBar/>

I have 2 fragments, let's say FragmentStart and FragmentToGoTo so in my navigation graph I have

<navigation
    android:id="@+id/navigation_graph.xml"
    app:startDestination="@id/fragmentStart">

    <fragment
        android:id="@+id/fragmentStart"
        android:name="com.FragmentStart">
        <action
            android:id="@+id/goToFragment"
            app:destination="@id/fragmentToGoTo" />
    </fragment>
    <fragment
        android:id="@+id/fragmentToGoTo"
        android:name="com.FragmentToGoTo"
        />
</navigation>

The Bottom App Bar menu has the item:

 <item
        android:id="@id/fragmentToGoTo"
        android:title="Title"
        app:showAsAction="always" />

Then on my activity

val navController = Navigation.findNavController(this, R.id.navigation_fragment)
myBottomBar.replaceMenu(R.menu.menu_with_nav_item)

myBottomBar.setupWithNavController(navController)
//or I've also tried
//NavigationUI.setupWithNavController(myBottomBar, navController, null)

What happens is that when clicking on the menu item, the navigation does not trigger and from what I've read, if the menu entry has the same id as the fragment in navigation graph, it should work directly. If I add OnMenuItemClickListener I can do on menu press do findNavController(R.id.navigation_fragment).navigate(R.id.fragmentToGoTo) and it works. I just would have liked an automatic way for this since it should be available.

What am I doing wrong?

Upvotes: 3

Views: 1308

Answers (1)

testgoofy
testgoofy

Reputation: 33

Hy

I'm new to Kotlin, but I had the same issue.

You also have to tie your menu with your navController with:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
  val navController = findNavController(R.id.fragmentContainer)
  return item.onNavDestinationSelected(navController) ||
    super.onOptionsItemSelected(item)
}

Just paste these code in your MainActivity.kt.

I've got the code from the Android docs: https://developer.android.com/guide/navigation/navigation-ui#Tie-navdrawer

Upvotes: 1

Related Questions