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

(gtxtreme123) #1

Chapter 13  The Toolbar


An Alternative Action Item


In this section, you will use what you have learned about menu resources to add an action item that lets
users show and hide a subtitle displaying the number of crimes from CrimeListActivity’s toolbar.


In res/menu/fragment_crime_list.xml, add an action item that will read SHOW SUBTITLE and will
appear in the toolbar if there is room. (The all-caps formatting is courtesy of the toolbar’s inherent
styles; you have seen similar formatting on buttons.)


Listing 13.12  Adding SHOW SUBTITLE action item
(res/menu/fragment_crime_list.xml)


<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/new_crime"
android:icon="@android:drawable/ic_menu_add"
android:title="@string/new_crime"
app:showAsAction="ifRoom|withText"/>


<item
android:id="@+id/show_subtitle"
android:title="@string/show_subtitle"
app:showAsAction="ifRoom"/>



Create a new method, updateSubtitle(), that will set the subtitle of the toolbar to display the number
of crimes.


Listing 13.13  Setting the toolbar’s subtitle (CrimeListFragment.java)


@Override
public boolean onOptionsItemSelected(MenuItem item) {
...
}


private void updateSubtitle() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeCount = crimeLab.getCrimes().size();
String subtitle = getString(R.string.subtitle_format, crimeCount);


AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(subtitle);
}
...


updateSubtitle() first generates the subtitle string using the getString(int resId, Object...
formatArgs) method, which accepts replacement values for the placeholders in the string resource.


Next, the activity that is hosting the CrimeListFragment is cast to an AppCompatActivity.
Recall that because CriminalIntent uses the AppCompat library, all activities are a subclass of
AppCompatActivity, which allows you to access the toolbar. (For legacy reasons, the toolbar is still
referred to as “action bar” in many places within the AppCompat library.)


Now that updateSubtitle() is defined, call the method when the user presses on the new action item.

Free download pdf