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

(gtxtreme123) #1

Chapter 13  The Toolbar


Next, modify the subtitle in onCreateOptionsMenu(...) and trigger a re-creation of the action items
when the user presses on the SHOW SUBTITLE action item.


Listing 13.16  Updating a MenuItem (CrimeListFragment.java)


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


MenuItem subtitleItem = menu.findItem(R.id.show_subtitle);
if (mSubtitleVisible) {
subtitleItem.setTitle(R.string.hide_subtitle);
} else {
subtitleItem.setTitle(R.string.show_subtitle);
}
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_crime:
...
case R.id.show_subtitle:
mSubtitleVisible = !mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateSubtitle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}


Finally, respect the mSubtitleVisible member variable when showing or hiding the subtitle in the
toolbar.


Listing 13.17  Showing or hiding the subtitle (CrimeListFragment.java)


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


if (!mSubtitleVisible) {
subtitle = null;
}


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


Run CriminalIntent and modify the subtitle visibility in the toolbar. Notice that the action item text
reflects the existence of the subtitle.

Free download pdf