Reputation: 8384
I have a ListActivity (SherlockListActivity
) and its content can be dynamically changed by the user. When the content changes, the options menu should be replaced.
As I learned, instead of onCreateOptionsMenu
I should use onPrepareOptionsMenu
that is (supposed to be) called every time the user selects the menu.
This is called right before the menu is shown, every time it is shown.
I have the following code:
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
menu.clear();
if (UserOption == UserOption1)
getSupportMenuInflater().inflate(R.menu.menu_option1, menu);
else
getSupportMenuInflater().inflate(R.menu.menu_option2, menu);
return super.onPrepareOptionsMenu(menu);
}
It is called only once during debug, so I always have the same menu.
What should I set to make it work?
Upvotes: 2
Views: 3387
Reputation: 622
Create and prepare the options menu for changing and its item selection method
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
MenuInflater inflater = getMenuInflater();
if(menuString=="red"){
inflater.inflate(R.menu.red_menu, menu);
}else if(menuString=="green"){
inflater.inflate(R.menu.green_menu, menu);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
return true;
case R.id.help:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Like whenever you want to change menu call
String menuString="red or green";
invalidateOptionsMenu();
Like others told, if you want to have static menu use onCreateOptionsMenu
, and if you want to change its visibility dynamically use onPrepareOptionsMenu
along with onCreateOptionsMenu
Upvotes: 4