Reputation: 1700
I have an action bar, that is being displayed when the program starts. One of its item ( id/action_delete' has its enabled attribute to false. How can I control it from other methods to make it true while the application is running.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.list_tasks, menu);
return super.onCreateOptionsMenu(menu);
}
A layout menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_delete"
android:showAsAction="always"
android:enabled="false"
android:title="Delete"/>
<item
android:id="@+id/action_new"
android:showAsAction="always"
android:title="New"/>
</menu>
the click event
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{
setStatus = true;
invalidateOptionsMenu();
}
the onPrepareOptionsMenu
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
MenuItem item = menu.findItem(R.id.action_delete_assignment);
if (setStatus)
{
item.setEnabled(true);
}
return super.onPrepareOptionsMenu(menu);
}
Upvotes: 1
Views: 107
Reputation: 227
I am not sure I understood your question. I guess that you want to dynamically change the action items in your action bar.
Use the onPrepareOptionsMenu() method.
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuItem item = menu.findItem(R.id.action_delete);
//show the action item
if (your condition) {
item.setEnabled(true);
item.setVisible(true);
}
super.onPrepareOptionsMenu(menu);
return true;
}
You should also override the invalidateOptionsMenu() method from the Activity class This will declare that the options menu has changed, and it will call the onPrepareOptionsMenu method to recreate the menu.
Upvotes: 2