Today I am going to show you how to create menu items dynamically. Some time we need to show menu items depending on different context (I mean data). Inflating menu using xml is very easy. but this also easy if you understand this well. So lets start with with android project.
First create new Android application project.This is example used API 11 and grater version if you need to support backward compatibility you have to use ActionBarSherlock or ActionBarCompat lib.
I added few icons to drawable folder and implement Activity like following.
Here you can see in onCreateOptionsMenu() .I added normal xml menu inflation and menu items by Java code.Here we can set every field that set from xml using java code.
defend on you context you can set different menu items.In my case mMenuSet=1 and mMenuSet=2 after changing context you can call invalidateOptionsMenu() to redraw menu item.
if you are using ActionBarSherlock you have to use Activity.supportInvalidateOptionsMenu() and ActionBarCompat invalidateOptionsMenu (Activity activity) method. you can download my example clicking following github icon.Then run it and see.