I want to go back to another fragment by pressing the back button. I already read, that the addToBackStack (String tag)
should help but it didn\'t really work.
I had the same situation before and I ended up with this solution. When you add or replace the Fragments, you need to add it to the backStack with a unique name. Then when the back button is pressed you can see which fragment was the active one with the method below inside the FragmentActivity that you created the Fragment.
private String getCurrentFragmentName() {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
String fragmentName;
if (backStackEntryCount > 0) {
fragmentName = getSupportFragmentManager().getBackStackEntryAt(backStackEntryCount - 1).getName();
} else {
fragmentName = "";
}
return fragmentName;
}
and in on onKeyDown() method do the following.
if (keyCode == KeyEvent.KEYCODE_BACK && getCurrentFragmentName().equals("your fragment name")) {
// Handle back press for this case.
return true;
} else if (keyCode == KeyEvent.KEYCODE_BACK
&& getCurrentFragmentName().equals("your another fragment")) {
// Handle back press for another Fragment
return true;
} else {
return super.onKeyDown(keyCode, event);
}
And this is the Place how I add the Fragment with backStack
transaction.addToBackStack("Your Fragment Name");