在导航抽屉中实现退出项

implement exit item in Navigation Drawer

我在我的项目中使用 android studio 的导航模板。我有两个项目可以浏览片段,我添加了另一个项目以通过 finish() 方法退出应用程序。问题是这个组件不使用 onNavigationItemSelected 并且当我尝试使用 navigationView.setNavigationItemSelectedListener() 我的退出项工作正常但片段切换不再工作。

这是我的代码:

public class MainActivity extends AppCompatActivity {

private AppBarConfiguration mAppBarConfiguration;
private ActivityMainBinding binding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    setSupportActionBar(binding.appBarMain.toolbar);
    binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
        @Override
        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(
            R.id.nav_home, R.id.nav_setting)
            .setDrawerLayout(drawer)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);
}

@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_content_main);
    return NavigationUI.navigateUp(navController, mAppBarConfiguration)
            || super.onSupportNavigateUp();
}
}

感谢 Martin Marconcini,我找到了解决方案。解决方案是:

NavigationUI.onNavDestinationSelected(dest, navController)

这是对我有帮助的一段代码:

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