I have my Activity and implements NavigationView.OnNavigationItemSelectedListener ,this is mi code is onCreate , don't print clicked too . previously it worked normal, without any inconvenience
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;
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
// 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.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
when i use onNavigationItemSelected(@NonNull MenuItem menuItem) , don't work but change fragments automatically
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
String title;
boolean fragmentTransaction = false;
Fragment fragment = null;
System.out.println("clicked");
switch (menuItem.getItemId()) {
case R.id.nav_home:
title = "MyText";
Bundle args = new Bundle();
args.putString("url", "MyText");
fragment.setArguments(args);
fragmentTransaction = true;
break;
case R.id.nav_gallery:
title = "MyText2";
Bundle args1 = new Bundle();
args1.putString("url", "My Text2");
fragment = new HomeFragment();
fragment.setArguments(args1);
fragmentTransaction = true;
break;
}
if (fragmentTransaction) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment_content_main, fragment)
.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
CodePudding user response:
if you want to implement your own NavigationItemSelectedListener, you shouldn't use the default setup in this line
NavigationUI.setupWithNavController(navigationView, navController);
and you should comment/remove it.
as if you inspected this method you will find it uses its own NavigationItemSelectedListener.