Search code examples
c#androidxamarinxamarin.androidandroid-toolbar

Xamarin Android toolbar how to add items dynamically


I have implemented android toolbar as per the instructions given in xamarin android guides here

using example code:

public override bool OnCreateOptionsMenu(IMenu menu)
        {           
            MenuInflater.Inflate(Resource.Menu.mainMenu, menu);

            return base.OnCreateOptionsMenu(menu);
        }

and xml :

<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:local="http://schemas.android.com/apk/res-auto">
  <item
       android:id="@+id/menu_share"
       local:showAsAction="ifRoom"
       android:title="Share" />
  <item
       android:id="@+id/menu_settings"
       local:showAsAction="ifRoom"
       android:title="Settings" />
</menu>

Now i want to add items to toolbar that will come from my web api , they are basically links to our pages such as privacy policy etc. but i cant find any example on menu.Add method that does this. basically what i need is to constrcut meny items from my json which returns:

[{
pageid:1,
pagename:"home",
pagehtmllink:"....."
},
{
pageid:2,
pagename:"About",
pagehtmllink:"....."
},
...........
]

how to achieve this from code behind?


Solution

  • IMenu has an Add method that you can call:

    public override bool OnCreateOptionsMenu(IMenu menu)
    {
            MenuInflater.Inflate(Resource.Menu.main_menu, menu);
    
            menu.Add(0, 99, 0, "DB Copy to SDCard (Debug)");
    
            return base. OnCreateOptionsMenu(menu);
    }
    

    For the parameters, review the Android docs: Menu.html#add

    To capture the menu selection, you can check the IMenuItem.ItemId value:

    public override bool OnOptionsItemSelected(IMenuItem item)
    {
        switch (item.ItemId)
        {
            case 99:
                DoSomething();
                return true;
            default:
                return false;
        }
    }