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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.