Orochi Orochi - 1 year ago 154
Android Question

How to go back to previous fragment from activity?

I've got an app with nav drawer, which is switching fragments. From inside one of those fragments, I am calling a new activity. When I click back in this activity (in toolbar), I want to go back to previous selected fragment but instead it puts me back to first fragment. I am adding my fragment to back stack so this should not be a problem.

Here is what I have already tried:

I have overriden the onBackPressed method in my 2nd activity like this:

public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
} else {

It is not working. I also saved index of current fragment inside onsaveinstancestate method and retrieve it but same result. I also tried with always putting current fragment inside variable and try to reshow it but still, it does not work. Anything else I could try?

Fun fact: if I press back inside bottom panel, it does actually goes back to previous fragment.

EDIT: Here is my code for doing this:

private void replaceFragment(Fragment fragment)
if (fragment != null)
FragmentManager manager = getSupportFragmentManager();
.replace(R.id.main_content, fragment)

I add first fragment only, if savedInstanceState is null, like so:

if (savedInstanceState == null) {
// first time
mTitle = getResources().getString(R.string.home);

And yes, all this is done inside onCreate() method.

Answer Source

I see, that people are still trying to help me. This answer helped me fix my problem: Android - Navigation Up from Activity to Fragment

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download