Reputation: 475
I have a Nav Drawer with a few items that I use with the new Navigation Architecture Component to navigate to different fragments. Now I have one item that should trigger an action (no navigation) but since the NavigationUI is already using the NavigationItemSelectedListener I can't add a second one.
NavigationUI.setupWithNavController(navView, findNavController(navHostFragment))
How can I handle the click of items that dont "navigate".
This seems to work without breaking the navigation:
navView.menu[3].setOnMenuItemClickListener
Upvotes: 3
Views: 424
Reputation: 2801
If you want to add an item with action but without layout, you can add your item to activity_main_drawer.xml file as below.
<item android:id="@+id/nav_test"
android:icon="@drawable/ic_menu_test"
android:title="Test" />
and in MainActivity.kt you can find item based on its id and set clickListener
navView.menu.findItem(R.id.nav_test).setOnMenuItemClickListener {
Log.d("MainActivity", "nav test clicked")
return@setOnMenuItemClickListener true
}
PS: Do not need to add the action/layout or item to mobile_navigation.xml file.
Happy coding :)
Upvotes: 1
Reputation: 321
I have same problem. I use navigationView.menu.getItem(3).setOnMenuItemClickListener
or navigationView.menu.findItem(R.id.action_delete_and_load).setOnMenuItemClickListener
Upvotes: 0
Reputation: 2785
You don't puted your code here, for this, I presume that you have an implementation of NavigationItemSelectedListener
on your Activity
. If yes, try pass the listener on your navView
as follow:
instead it:
navigationView.setNavigationItemSelectedListener(this);
try it:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//use just itens that "navigate"
return false;
}
});
Try update your ask with some code
Upvotes: 0