I have been using the old Android Studio and I had no problems with the navigation drawer template. I Updated my android studio to 3.5 and now I cannot seem to find am method that runs a function onClick on a certain menu item. I am trying to run a method where a navigation drawer item is clicked and a Toast Message is displayed. I have tried using navController.addOnDestinationChangedListener method but it only works on default fragments and when they are opened. I want the Toast message to be displayed without opening any fragment. This is how I have done it so far :
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
//removing tint
navigationView.setItemIconTintList(null);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.change_language, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull
NavDestination destination, @Nullable Bundle arguments) {
if (destination.getId() == R.id.nav_home) {
Toast.makeText(MainActivity.this, "Home has been clicked", Toast.LENGTH_LONG).show();
}
if (destination.getId() == R.id.nav_gallery) {
Toast.makeText(MainActivity.this, "Gallery Has been clicked", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}