2011-06-25 19 views
0

由於我動態地創建子菜單項,所以很顯然,MenuItems的索引將只是動態的。所以在這裏,我面臨的問題。動態處理Android中的SubMenu項目

到目前爲止,我已經成功地動態地創建內部onCreateOptionsMenu功能

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); 
} 

現在,當菜單項選擇中onOptionsItemSelected

//get the the selected index 
int selectedMenuIndex = item.getItemId();  

// Pass it to a function in another activity 
myList.myActivity.switch(selectedMenuIndex); 

//Finishing the current activity and loads the previously selected 
finish(); 

問題就來了菜單項每當父菜單加載和我點擊它以獲得子菜單,android會自動選擇列表中的第一個子菜單,即index = 0並立即觸發上面的代碼,並且不會等待子菜單的其餘部分加載並允許用戶從子菜單中選擇我已經動態創建。

回答

1

在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; 
    } 
}