Android add a menu item at runtime

自作多情 提交于 2019-12-24 04:37:56

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/5375645/android-add-a-menu-item-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!