开发者

Android add a menu item at runtime

开发者 https://www.devze.com 2023-02-17 21:55 出处:网络
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu);
@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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消