Android add a menu item at runtime

11,503

Menu items are not necessarily related to an activity like in the section suggested by Shelly, in which case you can call invalidateOptionsMenu() to get a hold on the menu object in order to "refresh" the menu in the subsequent call to onPrepareOptionsMenu().

From the same Android Developers site:

On Android 2.3.x and lower, the system calls onPrepareOptionsMenu() each time the user opens the options menu (presses the Menu button).

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

Share:
11,503
lacas
Author by

lacas

I am from Europe, Hungary. I am currently a php and android programmer.

Updated on June 04, 2022

Comments

  • lacas
    lacas almost 2 years
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
                case R.id.about:
                Intent i = new Intent(this, impresszum.class);
                startActivity(i);
    
                    return true;
                case R.id.quit:
                    AppUtils.ExitTheApplication();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
        }
    }
    

    I have this code. I want to add some menu at runtime, when i need it. And remove some menu when i need it. How can I do that?