dynamically handle SubMenu Items in android
As I am creating sub menu items dynamically , so its obvious that the MenuItems's index will be dynamic only. so here what i facing the problem.
so far i have successfully create the menu items dynamically inside onCreateOptionsMenu function
SubMenu switchMenu = menu.addSubMenu("My Menu");
for(int i=0;i<myList.getListSize();i++){
switchMenu.add(FILE, NEW_MENU_ITEM+i, 0, myList.get(i).data);
}
Now the problem comes when Menu Items are selected inside onOptionsItemSelected
//get the the selected index
int selectedMenuIndex = item.getItemId();
// Pass it to a function in anothe开发者_Go百科r activity
myList.myActivity.switch(selectedMenuIndex);
//Finishing the current activity and loads the previously selected
finish();
Whenever the parent menu loads and i click on it to get the submenu , android automatically selects first submenu in the list i.e. index =0 and immediately fires the above code and it doesn't wait for rest of the submenu to load and allow the user to select from the submens item that i have created dynamically.
Do this in your OnOptionsItemSelected
public boolean onOptionsItemSelected(MenuItem item)
{
if( (item.getItemId() & NEW_MENU_ITEM ) == NEW_MENU_ITEM) // check if its a sub menu ID
{
switch(item.getItemId() - NEW_MENU_ITEM)
{
case 0: // first sub menu option
{
DoSubMenu1();
break;
}
case 1:: // second sub menu option
{
DoSubMenu2();
break;
}
// and so on ..................
}
return;
}
}
精彩评论