1

我一直在使用旧的 Android Studio,并且导航抽屉模板没有问题。我将我的 android studio 更新到 3.5,现在我似乎找不到在某个菜单项上运行 onClick 函数的方法。我正在尝试运行一种方法,其中单击导航抽屉项目并显示 Toast 消息。我曾尝试使用 navController.addOnDestinationChangedListener 方法,但它仅适用于默认片段以及打开它们时。我希望在不打开任何片段的情况下显示 Toast 消息。到目前为止,我就是这样做的:

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();
}
4

0 回答 0