Responding to menu selections
Responding to menu selections
To respond to the user pressing the New Crime action item, you need a way to add a new Crime to your
list of crimes. In CrimeLab.java, add a method to do this.
Listing 13.8 Adding a new crime (CrimeLab.java)
...
public void addCrime(Crime c) {
mCrimes.add(c);
}
public List
return mCrimes;
}
In this brave new world where you will be able to add crimes yourself, the 100 programmatically
generated crimes are no longer necessary. Remove the code that generates these crimes from
CrimeLab.java.
Listing 13.9 Goodbye, random crimes! (CrimeLab.java)
private CrimeLab(Context context) {
mCrimes = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Crime crime = new Crime();
crime.setTitle("Crime #" + i);
crime.setSolved(i % 2 == 0); // Every other one
mCrimes.add(crime);
}
}
When the user presses an action item, your fragment receives a callback to the method
onOptionsItemSelected(MenuItem). This method receives an instance of MenuItem that describes the
user’s selection.
Although your menu only contains one action item, menus often have more than one. You can
determine which action item has been selected by checking the ID of the MenuItem and then respond
appropriately. This ID corresponds to the ID you assigned to the MenuItem in your menu file.