@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);
}
}
我有这个代码。我想在运行时添加一些菜单,当我需要的时候。当我需要时删除一些菜单。我怎样才能做到这一点?
最佳答案
菜单项不一定与 Shelly 建议的部分中的 Activity 相关,在这种情况下,您可以调用 invalidateOptionsMenu()
来保留菜单对象以便“刷新”后续调用 onPrepareOptionsMenu()
中的菜单。
来自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().
关于Android 在运行时添加菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5375645/