当我使用 onCreateOptionsMenu
或 onOptionsItemSelected
方法时,我可以轻松做到这一点。
但我在屏幕某处有一个按钮,单击该按钮时,它应该启用/禁用上下文菜单项。
最佳答案
无论如何,the documentation涵盖所有内容。
在运行时更改菜单项
Once the activity is created, the
onCreateOptionsMenu()
method is called only once, as described above. The system keeps and re-uses theMenu
you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override theonPrepareOptionsMenu()
method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.
例如
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
if (isFinalized) {
menu.getItem(1).setEnabled(false);
// You can also use something like:
// menu.findItem(R.id.example_foobar).setEnabled(false);
}
return true;
}
在 Android 3.0 及更高版本上,当菜单项出现在操作栏中时,选项菜单被视为始终处于打开状态。当事件发生时,你要进行菜单更新,你必须调用invalidateOptionsMenu()
来请求系统调用onPrepareOptionsMenu()
。
关于Android:如何在按钮单击时启用/禁用选项菜单项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5440601/