Android MenuThe callback time of the menu
There are three main callbacks that are commonly associated with menus:
//创建菜单的时候调用public boolean onCreateOptionsMenu(Menu menu);//显示菜单的时候调用public boolean onPrepareOptionsMenu(Menu menu);//选择菜单项的时候调用public boolean onOptionsItemSelected(MenuItem item);
Modify View
Therefore, if we want to customize the display of menus, we should intervene in the creation process when creating menu items, but this process is not open to developers.
In this case, we can either re-customize the entire menu view, or after the system creation number, to modify each one.
In the latter case, we can modify each item in Oncreateoptionsmenu, the main method is to simulate by Actionview:
MenuItem.setActionView(actionView);或者MenuItemCompat.setActionView(menuItem, actionView);//兼容包
For example, replace with TextView:
TextView action = new TextView(this);action.setText(menuItem.getTitle());action.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onOptionsItemSelected(menuItem); }});MenuItemCompat.setActionView(menuItem, action);
Dynamic modification
Sometimes you need to modify the menu dynamically, this time need to divide the situation, for those that are collected in the menu, can be onprepareoptionsmenu in the dynamic increase or decrease,
Because Onprepareoptionsmenu will be called every time the menu is displayed to the user (e.g. click on the "More" button on the Actionbar).
However, if the menu that needs to be modified is always displayed on Actionbar or toolbar, it will not involve onprepareoptionsmenu when the menu event is triggered, this time you can recreate the menu, use
Activity.invalidateOptionsMenu()或者ActionBarActivity.supportInvalidateOptionsMenu()//兼容包
To re-enter the menu flow.
Demo diagram
Demo Source
Android_menu
Android Share Q Group: 315658668
"Android" Modify Menu