lacas
lacas

Reputation: 14066

Android add a menu item at runtime

@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?

Upvotes: 2

Views: 11568

Answers (1)

stemadsen
stemadsen

Reputation: 1901

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().

Upvotes: 3

Related Questions