2

I am working on xamarin android application.I am not able to create OptionMenu in Fragments. I have tried this code but not worked.

public override void OnCreateOptionsMenu (IMenu menu, MenuInflater inflater){
    inflater.Inflate(Resource.Layout.Menu,menu);
    base.OnCreateOptionsMenu (menu, inflater);
}

What is the solution?

michoprogrammer
  • 1,159
  • 2
  • 18
  • 45
Dhruv Gohil
  • 335
  • 4
  • 12

3 Answers3

3

You need to add setHasOptionsMenu(true); in onCreate();

Please refer this link :

https://stackoverflow.com/a/8309255/3118054

Community
  • 1
  • 1
Darsh Patel
  • 1,015
  • 9
  • 15
1

on your methode public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) in the fragment add this instruction

HasOptionMenu=true;

and then you have to override the method OnCreateOptionsMenu(IMenu menu, MenuInflater inflater) in your fragment like this

public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
    {
        inflater.Inflate(Resource.Menu.menu_search1, menu);
        base.OnCreateOptionsMenu(menu, inflater);

        var searchItem = menu.FindItem(Resource.Id.action_search);
        searchItem.SetVisible(true);

    }
Younes
  • 46
  • 2
0

You do not add Options menu in Fragments but in FragmentActivity and that FragmentActivity will act like container which will contain your fragments as well as your OptionsMenu.

Fragments basically replaces a Layout from where they are called, so you would have to use the CreateOptionsMenu from where you are calling that Fragment.

ARKhan
  • 297
  • 1
  • 9
  • It is mentioned perfectly.If i take activity then I can add OptionMenu.But for Fragments it is not working – Dhruv Gohil Sep 10 '15 at 14:25
  • You tried Option menu in your MainActivity or whatever activity you are calling the Fragment from? – ARKhan Sep 10 '15 at 14:30