JCDecary
JCDecary

Reputation: 607

How can i add options menu to fragment from NavigationView

Hi i'm having a little bit of trouble, i'm trying to add options menu into my fragment (VoiceCoiSelectionFragment) i have this navigation graph

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/communication_menu_graph"
    app:startDestination="@id/commMenuFragment">
    <fragment
        android:id="@+id/commMenuFragment"
        android:name="ca.stackoverflow.menu.comm_menu.CommMenuFragment"
        android:label="@string/comm_menu_label"
        tools:layout="@layout/fragment_comm_menu">
        <action
                android:id="@+id/action_commMenu_to_voiceCois"
                app:destination="@+id/voiceCoi" />
    </fragment>
    <fragment
            android:id="@+id/voiceCoi"
            android:name="ca.stackoverflow.VoiceCoiSelectionFragment"
            android:label="@string/voiceCoi"
            tools:layout="@layout/coi_panel" />
</navigation>

on the button click i have

NavHostFragment.findNavController(this).navigate(CommMenuFragmentDirections.actionCommMenuToVoiceCois())

In my VoiceCoiSelectionFragment i try to add hasOptionsMenu to true than inflate it in

 @Override
    public void onCreateOptionsMenu(@NonNull final Menu menu, @NonNull final MenuInflater inflater)
    {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.saving, menu);
    }

The onCreate of my activity contain

NavigationUI.setupWithNavController(_viewBinding.menuAppBar, _navController, menuAppBarConfig);
        _viewBinding.menuAppBar.setNavigationIcon(ca.rheinmetall.argus.R.drawable.ic_arrow_back_white_24dp);
        _viewBinding.menuAppBar.setNavigationOnClickListener(v -> onBackPressed());

but it doesn't work do i missing something ?

Upvotes: 0

Views: 59

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 200120

The Fragment menu APIs require two things:

  1. That you have an ActionBar at the activity level via the correct theme or by using setSupportActionBar()

  2. That you call setHasOptionsMenu(true) in your Fragment's onCreate()

Make sure you have done both things.

Upvotes: 1

Related Questions