“Just one more thing...”
“Just one more thing...”
Programming in Android is often like being questioned by the TV detective Columbo. You think you
have the angles covered and are home free. But Android always turns at the door and says, “Just one
more thing...”
Here, there are actually two more things. First, when creating a new crime and then returning to
CrimeListActivity with the Back button, the number of crimes in the subtitle will not update to
reflect the new number of crimes. Second, the visibility of the subtitle is lost across rotation.
Tackle the update issue first. The solution to this problem is to update the subtitle text when returning
to CrimeListActivity. Trigger a call to updateSubtitle() in onResume(). Your updateUI() method
is already called in onResume() and onCreateView(...). Add a call to updateSubtitle() to the
updateUI() method.
Listing 13.18 Showing the most recent state (CrimeListFragment.java)
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List
if (mAdapter == null) {
mAdapter = new CrimeAdapter(crimes);
mCrimeRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.notifyDataSetChanged();
}
updateSubtitle();
}
Run CriminalIntent, show the subtitle, create a new crime, and press the Back button on the device to
return to CrimeListActivity. The number of crimes in the toolbar will be correct.
Now repeat these steps, but instead of using the Back button, use the Up button in the toolbar. The
visibility of the subtitle will be reset. Why does this happen?
An unfortunate side effect of the way hierarchical navigation is implemented in Android is that the
activity that you navigate up to will be completely re-created from scratch. This means that any
instance variables will be lost, and it also means that any saved instance state will be lost as well. This
parent activity is seen as a completely new activity.
There is not an easy way to ensure that the subtitle stays visible when navigating up. One option is to
override the mechanism that navigates up. You could call finish() on the CrimePagerActivity to pop
back to the previous activity. This would work perfectly well in CriminalIntent but would not work in
apps with a more realistic hierarchy, as this would only pop back one activity.
Another option is to pass information about the subtitle visibility as an extra to CrimePagerActivity
when it is started. Then, override the getParentActivityIntent() method in CrimePagerActivity
to add an extra to the intent that is used to re-create the CrimeListActivity. This solution requires
CrimePagerActivity to know the details of how its parent works.
Both of these solutions are less than ideal, and there is not a great alternative. For this reason, you are
going to let this issue ride; making the user click SHOW SUBTITLE is not a terrible burden.