I have an Activity
where I load in a ListFragment
and, upon clicking, it drills down a level and a new type of ListFragment
is shown,
It is best to let the OS do as much of the work as possible. Assuming each fragment is properly named using .addToBackStack("title") then you can override onBackPressed something like this to achieve desired behavior:
// this example uses the AppCompat support library
// and works for dynamic fragment titles
@Override
public void onBackPressed() {
FragmentManager fragmentManager = getSupportFragmentManager();
int count = fragmentManager.getBackStackEntryCount();
if (count <= 1) {
finish();
}
else {
String title = fragmentManager.getBackStackEntryAt(count-2).getName();
if (count == 2) {
// here I am using a NavigationDrawer and open it when transitioning to the initial fragment
// a second back-press will result in finish() being called above.
mDrawerLayout.openDrawer(mNavigationDrawerFragment.getView());
}
super.onBackPressed();
Log.v(TAG, "onBackPressed - title="+title);
getSupportActionBar().setTitle(title);
}
}