Enabling Up (ancestral) navigation in Android apps is straightforward for the typical case: just specify parent activities in the manifest and send setDisplayHomeAsUpEnabled(true). But non-typical cases (like dynamic parents) require extra steps.
Today I implemented some non-typical cases and experimented with overriding action bar callbacks, tweaking the back stack, etc. But in most cases I simply wanted up navigation to behave like back navigation whenever there was no fixed parent defined. For that, I developed a simple recipe:
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (NavUtils.getParentActivityName(getActivity()) != null) { NavUtils.navigateUpFromSameTask(getActivity()); } else { getActivity().onBackPressed(); } return true; default: return super.onOptionsItemSelected(item); } } |