"Android" Modify Menu

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.