Sometimes we need to load multiple menu files in an activity. For example, to achieve the following results:
1. We have a drop-down list. When we select the first drop-down item and press the menu key, the first menu is displayed;
2. Select the second drop-down item and press the menu key to bring up the second menu.
How can we achieve this effect?
Select the first entry for the spinner. The menu1 menu is displayed.
Select menu2 for the spinner. The menu2 menu is displayed.
I. The first idea is to create two menu. xml files. Then, in the onprepareoptionsmenu (menu) method, first judge the value of the spinner, and then load different menu. xml files according to different values.
Code:
Int Index = spinner. getselecteditemposition ();
If (Index = 0 ){
Menuinflater Inflater = getmenuinflater ();
Inflater. Inflate (R. Menu. menu1, menu );
}
Else if (Index = 1 ){
Menuinflater Inflater = getmenuinflater ();
Inflater. Inflate (R. Menu. menu2, menu );
}
However, the experiment found that this method is not feasible because the menu value in the menuinflater class cannot be reduced but can only be increased. In other words, when you select index = 0 for the first time, click menu, select index = 1, and then click menu, the menu with Index = 0 is still selected, and cannot be deleted.
In addition, an activity corresponds to a menuinflater. Therefore, this menuinflater cannot be cloned (You have tried it yourself, but not ). Therefore, this method does not work.
II. Second idea: I later found that menu has a group subnode, which has a visible attribute to show whether the group is visible. Therefore, we can write two menu files in one file and write them into two groups. Then, we can control the visibility of the group based on the different values of the spinner.
So the code becomes as follows:
Public Boolean onprepareoptionsmenu (menu ){
Int Index = spinner. getselecteditemposition ();
If (Index = 0 ){
Menu. setgroupvisible (R. Id. menu1, true );
Menu. setgroupvisible (R. Id. menu2, false );
}
Else if (Index = 1 ){
Menu. setgroupvisible (R. Id. menu1, false );
Menu. setgroupvisible (R. Id. menu2, true );
}
Return true;
}
In this way, the effect is achieved.