Search code examples
androidandroid-fragmentsandroid-activityandroid-toolbarandroid-navigation

How can I navigate from the MenuItem to a fragment (Android)?


I have a MainActivity and 3 different Fragments. The toolbar I created in MainActivity appears in all 3 Fragments I have. And I can switch between these Fragments using the button.

As an example;

binding.buttonSelectFile.setOnClickListener(v -> NavHostFragment.findNavController(FirstFragment.this)
                .navigate(R.id.action_FirstFragment_to_ThirdFragment));

I want to create a similar behavior for the Toolbar item. For example, every time the user presses a "help" item defined as below, I want the application to navigate to the HelpFragment.

<menu 
    <!-- other items -->
    <item
        android:id="@+id/action_help"
        android:orderInCategory="100"
        android:title="@string/action_help"
        app:showAsAction="never" />
</menu>

I tried to do something like this in the onCreate() method of the MainActivity class, purely as a guess.

binding.toolbar.getMenu().getItem(R.id.action_help).setOnMenuItemClickListener(item -> {
            Navigation.findNavController(view).navigate(R.id.HelpFragment);
            return true;
        });

However, this method is of course not correct.

Is such use possible? Or should I follow another way to show the help screen to the user?


Solution

  • I am calling the setSupportActionBar() method for it

    So, the action_help menu item is a part of the default optionsMenu. Then you need to override onCreateOptionsMenu() to inflate the menu, and onOptionsItemSelected to handle the click on the R.id.action_help menu item.

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu, menu); // replace "my_menu" with the name of your menu xml file
        return true;
    }
    
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    
        if (item.getItemId() == R.id.action_help) {
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); // replace "nav_host_fragment" with the id of your navHostFragment in activity layout
            navController.navigate(R.id.HelpFragment);
            return true;
        } 
        return super.onOptionsItemSelected(item);
    
    }