[英]implement exit item in Navigation Drawer
I'm using navigation template of android studio in my project.我在我的项目中使用了 android studio 的导航模板。 I have two items to navigate through fragments and I added another item to exit the app via finish() method.
我有两个项目可以在片段中导航,我添加了另一个项目以通过 finish() 方法退出应用程序。 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.
问题是这个组件不使用 onNavigationItemSelected 并且当我尝试使用 navigationView.setNavigationItemSelectedListener() 我的退出项工作正常但片段切换不再工作。
Here's my code:这是我的代码:
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();
}
}
I found the solution thanks to Martin Marconcini .感谢Martin Marconcini ,我找到了解决方案。 Solution is:
解决方案是:
NavigationUI.onNavDestinationSelected(dest, navController)
Here's the piece of code that helped me:这是帮助我的一段代码:
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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.