Use of onPrepareOptionsMenu


#1

I have a very basic question: why can you not just toggle the menu title within the Case statement in onOptionsItemSelected? Why do you have to use onPrepareOptionsMenu instead?

In other words, why wouldn’t the following code work:

case R.id.menu_item_toggle_polling: boolean shouldStartAlarm = !PollService.isServiceAlarmOn(getActivity()); PollService.setServiceAlarm(getActivity(), shouldStartAlarm); if (shouldStartAlarm) { item.setTitle(R.string.stop_polling); } else { item.setTitle(R.string.start_polling); } return true;


#2

(sorry for the late reply)
In short it will work. You are basically changing the text as soon as you click the menu item, so that the next time you bring up the options menu/dialog its already set.

However what happens if we add some functionality later that turns off the polling service (say we want to automatically turn polling off after 3 hours). We would have to remember to manually update the options menu/dialog. Thats a lot to expect =P

In the end you’ve violated a DRY principle. You have the state of service stored in two places: the menu item button and PollingService.isServiceAlarmOn(.). Which one is the truth? What if a new developer came onto the project? He might think "hey the button state is set to “stop polling so the service must be running.” He would be sad to find out he was wrong.

Instead if we put the text changing inside onPrepareOptionsMenu() we know that

  1. it will get set at the exact right moment (as soon as we are about to see the options menu)
  2. the ground truth about the state of the service is stored in exactly one place: PollingService.isServiceAlarmOn(.)