0

I am using navigation component in my app. I am trying to navigate to the Fragment on click of an action bar icon, but it is not working. Below is my code:

action_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:title=""
    android:id="@+id/cart_notif"
    android:icon="@drawable/ic_order"
    app:showAsAction="always"
    android:actionLayout="@layout/notification_badge"/>

</menu> 

nav_host.xml

 <fragment
    android:id="@+id/cartFragment"
    android:name="BottomFragments.CartFragment"
    android:label="Cart"
    tools:layout="@layout/fragment_cart">

    <action
        android:id="@+id/action_cartFragment_to_cakeFragment"
        app:destination="@id/cakeFragment"
        app:enterAnim="@anim/nav_default_enter_anim"
        app:popUpTo="@id/cakeFragment"
        app:popUpToInclusive="true" />
</fragment>

MainActivity.java

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

   if(item.getItemId() == R.id.cart_notif){
       NavController navController = Navigation.findNavController(MainActivity.this,R.id.fragment);
       navController.navigate(R.id.cartFragment);
     }

    return super.onOptionsItemSelected(item);
}

@Override
public boolean onSupportNavigateUp() {
     navController.navigateUp();
    return super.onSupportNavigateUp();
}

This approach is not working - how can I navigate?

halfer
  • 19,824
  • 17
  • 99
  • 186
Digvijay
  • 2,887
  • 3
  • 36
  • 86

1 Answers1

0

here I can see you are using onOptionsItemSelected for navigating from one screen to another. Instead you should use onNavigationItemSelected method.

See this answer for more details.

WhiteSpidy.
  • 1,107
  • 1
  • 6
  • 28