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

(gtxtreme123) #1

Chapter 13  The Toolbar


Creating the menu


In code, menus are managed by callbacks from the Activity class. When the menu is needed, Android
calls the Activity method onCreateOptionsMenu(Menu).


However, your design calls for code to be implemented in a fragment, not an activity. Fragment comes
with its own set of menu callbacks, which you will implement in CrimeListFragment. The methods for
creating the menu and responding to the selection of an action item are:


public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
public boolean onOptionsItemSelected(MenuItem item)


In CrimeListFragment.java, override onCreateOptionsMenu(Menu, MenuInflater) to inflate the
menu defined in fragment_crime_list.xml.


Listing 13.6  Inflating a menu resource (CrimeListFragment.java)


@Override
public void onResume() {
super.onResume();
updateUI();
}


@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
}
...


Within this method, you call MenuInflater.inflate(int, Menu) and pass in the resource ID of your
menu file. This populates the Menu instance with the items defined in your file.


Notice that you call through to the superclass implementation of onCreateOptionsMenu(...). This
is not required, but we recommend calling through as a matter of convention. That way, any menu
functionality defined by the superclass will still work. However, it is only a convention – the base
Fragment implementation of this method does nothing.


The FragmentManager is responsible for calling Fragment.onCreateOptionsMenu(Menu,
MenuInflater) when the activity receives its onCreateOptionsMenu(...) callback from the
OS. You must explicitly tell the FragmentManager that your fragment should receive a call to
onCreateOptionsMenu(...). You do this by calling the following method:


public void setHasOptionsMenu(boolean hasMenu)

Free download pdf