Chapter 13 The Toolbar
In CrimeListFragment.java, implement onOptionsItemSelected(MenuItem) to respond to selection
of the MenuItem by creating a new Crime, adding it to CrimeLab, and then starting an instance of
CrimePagerActivity to edit the new Crime.
Listing 13.10 Responding to menu selection (CrimeListFragment.java)
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_crime:
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity
.newIntent(getActivity(), crime.getId());
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Notice that this method returns a boolean value. Once you have handled the MenuItem, you should
return true to indicate that no further processing is necessary. The default case calls the superclass
implementation if the item ID is not in your implementation.
Run CriminalIntent and try out your new menu. Add a few crimes and edit them afterward. (The empty
list that you see before you add any crimes can be disconcerting. At the end of this chapter there is a
challenge to present a helpful clue when the list is empty.)
Enabling Hierarchical Navigation
So far, CriminalIntent relies heavily on the Back button to navigate around the app. Using the Back
button is temporal navigation. It takes you to where you were last. Hierarchical navigation, on the
other hand, takes you up the app hierarchy. (It is sometimes called ancestral navigation.)
In hierarchical navigation, the user navigates up by pressing the Up button on the left side of the
toolbar.
Enable hierarchical navigation in CriminalIntent by adding a parentActivityName attribute in the
AndroidManifest.xml file.