Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 28  Background Services


In onCreateOptionsMenu(...), check whether the alarm is on and change the text of
menu_item_toggle_polling to show the appropriate label to the user.


Listing 28.14  Toggling the menu item (PhotoGalleryFragment.java)


public class PhotoGalleryFragment extends Fragment {
private static final String TAG = "PhotoGalleryFragment";
...
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
super.onCreateOptionsMenu(menu, menuInflater);
menuInflater.inflate(R.menu.fragment_photo_gallery, menu);


MenuItem searchItem = menu.findItem(R.id.menu_item_search);
final SearchView searchView = (SearchView) searchItem.getActionView();


searchView.setOnQueryTextListener(...);


searchView.setOnSearchClickListener(...);


MenuItem toggleItem = menu.findItem(R.id.menu_item_toggle_polling);
if (PollService.isServiceAlarmOn(getActivity())) {
toggleItem.setTitle(R.string.stop_polling);
} else {
toggleItem.setTitle(R.string.start_polling);
}
}
...
}


Next, in onOptionsItemSelected(MenuItem), tell PhotoGalleryActivity to update its toolbar
options menu.


Listing 28.15  Invalidating your options menu (PhotoGalleryFragment.java)


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_clear:
...
case R.id.menu_item_toggle_polling:
boolean shouldStartAlarm = !PollService.isServiceAlarmOn(getActivity());
PollService.setServiceAlarm(getActivity(), shouldStartAlarm);
getActivity().invalidateOptionsMenu();
return true;
default:
return super.onOptionsItemSelected(item);
}
}


With that, your code to toggle the options menu contents should work great. And yet... there is
something missing.

Free download pdf