My application's main Activity is a TabActivity and it contains an OptionsMenu. I define some other Activities (which go into a tab) and I would like to define a menu in each of these activities and have its menu merged with the main one. Is it possible?
问题:
回答1:
Yes, this is possible. Basically you just inflate multiple xml files into the same options menu. Items are added to the menu in order of inflation.
Just overwrite onCreateOptionsMenu(Menu menu)
for your TabActivity
, inflating the xml file containing the main options. Then overwrite it for each of your inner tab activities, inflating the tab-specific options. Just write them as you usually would:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.options, menu);
return super.onCreateOptionsMenu(menu);
}
The menu 'belongs' to the currently active inner tab activity, but to populate it, onCreateOptionsMenu
is automatically called on the parent activities too (by super
).
However, strangely, onMenuItemSelected(int featureId, MenuItem item)
does not do the same. To handle item selection, the inner tab activities still have to explicitly call the corresponding method on the parent activity (after you determine that the selected option is not tab-specific):
return super.onMenuItemSelected(featureId, item)
|| getParent().onMenuItemSelected(featureId, item);
回答2:
Are you creating the menus dynamically or in separate XMLs?
if Dynamically you can just set it up as
public void createMenu()
{
//Main Menu here
switch(tab)
{
case '1': //add tab 1 menu
break;
case '2': //add tab 2 menu
break;
}
}