implement exit item in Navigation Drawer


I’m using navigation template of android studio in my project. I have two items to navigate through fragments and I added another item to exit the app via finish() method. The problem is this component doesn’t use onNavigationItemSelected and when I try to use navigationView.setNavigationItemSelectedListener() my exit item works fine but fragment switching doesn’t work any more.

Here’s my code:

public class MainActivity extends AppCompatActivity {

private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;

protected void onCreate(Bundle savedInstanceState) {

    binding = ActivityMainBinding.inflate(getLayoutInflater());

    binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
    DrawerLayout drawer = binding.drawerLayout;
    NavigationView navigationView = binding.navView;
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(
    NavController navController = Navigation.findNavController(this,;
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(, menu);
    return true;

public boolean onSupportNavigateUp() {
    NavController navController = Navigation.findNavController(this,;
    return NavigationUI.navigateUp(navController, mAppBarConfiguration)
            || super.onSupportNavigateUp();


I found the solution thanks to Martin Marconcini . Solution is :

NavigationUI.onNavDestinationSelected(dest, navController)

Here’s the piece of code that helped me :

navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {
            if (item.getItemId() == {
            } else {
                NavigationUI.onNavDestinationSelected(item, navController);
            return false;

Answered By – Android Lover Boy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published