Fragment callback interfaces
In CrimeListActivity.java, implement onCrimeSelected(Crime) to handle the selection of a crime
in either interface.
Listing 17.8 Conditional CrimeFragment startup (CrimeListActivity.java)
@Override
public void onCrimeSelected(Crime crime) {
if (findViewById(R.id.detail_fragment_container) == null) {
Intent intent = CrimePagerActivity.newIntent(this, crime.getId());
startActivity(intent);
} else {
Fragment newDetail = CrimeFragment.newInstance(crime.getId());
getSupportFragmentManager().beginTransaction()
.replace(R.id.detail_fragment_container, newDetail)
.commit();
}
}
Finally, in CrimeListFragment, you are going to call onCrimeSelected(Crime) in the places where
you currently start a new CrimePagerActivity.
In CrimeListFragment.java, modify onOptionsItemSelected(MenuItem) and
CrimeHolder.onClick(View) to call Callbacks.onCrimeSelected(Crime).
Listing 17.9 Calling all callbacks! (CrimeListFragment.java)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_crime:
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity
.newIntent(getActivity(), crime.getId());
startActivity(intent);
updateUI();
mCallbacks.onCrimeSelected(crime);
return true;
...
}
}
...
private class CrimeHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
...
@Override
public void onClick(View view) {
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
mCallbacks.onCrimeSelected(mCrime);
}
}
When you call back in onOptionsItemSelected(MenuItem), you also reload the list immediately upon
adding a new crime. This is necessary because, on tablets, the list will remain visible after adding a
new crime. Before, you were guaranteed that the detail screen would appear in front of it.