Search code examples
androidxamarinxamarin.android

OnCreateOptionsMenu not called after updating code to AndroidX


I recently updated my Xamarin.Android project to AndroidX code. In my fragment, OnCreateOptionsMenu would get called, but it is not called anymore after changing my fragment to AndroidX.Fragment.App.Fragment. I would call SetHasOptionsMenu(true) but that method does not exist anymore. So I try this in my OnCreateView instead:

View view = inflater.Inflate(Resource.Layout.my_layout, container, false);
AndroidX.AppCompat.Widget.Toolbar toolbar = view.FindViewById<AndroidX.AppCompat.Widget.Toolbar>(Resource.Id.drawerToolbar);
(this.Activity as AndroidX.AppCompat.App.AppCompatActivity).SetSupportActionBar(toolbar);
var actionBar = (this.Activity as AndroidX.AppCompat.App.AppCompatActivity).SupportActionBar;
if(actionBar != null)
{
    actionBar.SetDisplayShowTitleEnabled(false);
}

actionBar.SetDisplayShowTitleEnabled gets called but my override of OnCreateOptionsMenu is still not called.

public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
{
    // never get called
}

Solution

  • You need to tell the fragment that he has a menu.

    HasOptionsMenu = true