可以使用addSubMenu()把子菜單添加到現有的菜單. 這將返回一個子菜單(SubMenu)對象. 然後, 您可以把額外的項目添加到這個菜單上.
修改主程序, 重寫onCreateOptionsMenu(Menu)和onOptionsItemSelected(MenuItem):
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
boolean result = super.onCreateOptionsMenu(menu);
SubMenu Menu_1 = menu.addSubMenu(0, 0, 0, "Menu_1");
Menu_1.add(0, 1, 0, "Sub Menu 1 1");
Menu_1.add(0, 2, 0, "Sub Menu 1 2");
Menu_1.add(0, 3, 0, "Sub Menu 1 3");
SubMenu Menu_2 = menu.addSubMenu(1, 4, 0, "Menu_2");
Menu_2.add(1, 5, 0, "Sub Menu 2 1");
Menu_2.add(1, 6, 0, "Sub Menu 2 2");
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
String myMenuitem = null;
switch(item.getItemId()){
case 0:
myMenuitem = "Menu 1";
break;
case 1:
myMenuitem = "Sub Menu 1 1";
break;
case 2:
myMenuitem = "Sub Menu 1 2";
break;
case 3:
myMenuitem = "Sub Menu 1 3";
break;
case 4:
myMenuitem = "Menu 2";
break;
case 5:
myMenuitem = "Sub Menu 2 1";
break;
case 6:
myMenuitem = "Sub Menu 2 2";
break;
}
Toast.makeText(this, myMenuitem, Toast.LENGTH_LONG).show();
return true;
}
除了使用addSubMenu()外, 子菜單(sub menu)亦可以使用XML定義.
沒有留言:
發佈留言