Android: How to enable/disable option menu item on button click?
I can easily do it when I am using onCreateOptionsMenu
or onOptionsItemSelected
methods.
But I have a button somewhere in screen, and on clicking that button, it should enable/disable context menu items.
Thanks...
Anyway, the documentation covers all the things.
Changing menu items at runtime
Once the activity is created, the onCreateOptionsMenu()
method is called only once, as described above. The system keeps and re-uses the Menu
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 the onPrepareOptionsMenu()
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.
Eg
@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;
}
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版本中,最简单的方法是:使用此选项将菜单操作图标显示为已禁用,并将其功能设为已禁用:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.menu_my_item);
if (myItemShouldBeEnabled) {
item.setEnabled(true);
item.getIcon().setAlpha(255);
} else {
// disabled
item.setEnabled(false);
item.getIcon().setAlpha(130);
}
}
您可以在创建选项菜单时将该项目保存为变量,然后随意更改其属性。
private MenuItem securedConnection;
private MenuItem insecuredConnection;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.connect_menu, menu);
securedConnection = menu.getItem(0);
insecuredConnection = menu.getItem(1);
return true;
}
public void foo(){
securedConnection.setEnabled(true);
}
链接地址: http://www.djcxy.com/p/57382.html