0

I have a simple problem. My problem is that I have two activities:

  • Activity A
  • Activity B

In Activity A I display 4-5 fragments. That is the main activity (Navigation Drawer) so I display 4-5 fragments in it.

From all fragments it redirects to Activity B.

But I want to display the last opened fragment when I come back from Activity B.

Now it directly opens the first fragment, which is the default. I want to open the last opened fragment when the user returns to the first activity.

Please help me...

Aaaaaa1212
  • 39
  • 1
  • 5

3 Answers3

0

If your first activity changes with the second one, then fragments of the former activity will destroy themself because of the activity lifecycle.

You should just open first activity using startActivity and store the last active fragment before it goes the letter activity.

ziLk
  • 3,120
  • 21
  • 45
0

You don't use finish while call second activity. For exp: `

 Intent i = new Intent(getApplicationContext(), ActivityB.class);
 startActivity(i);
 //finish(); `
John Joe
  • 12,412
  • 16
  • 70
  • 135
0

You can use onSaveInstanceState in Activity A to save information about last opened fragment and onRestoreInstanceState/onCreate to restore this information. For example:

private static final String LAST_OPENED_FRAGMENT_REF = "LAST_OPENED_FRAGMENT_REF";
private static final int HOME_FRAGMENT = 0;
private static final int OTHER_FRAGMENT = 1;

private int currentOpenedFragment = HOME_FRAGMENT;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    if (savedInstanceState != null) {
        currentOpenedFragment = savedInstanceState.getInt(LAST_OPENED_FRAGMENT_REF);
    }
    if (navigationView != null) {
        Fragment fragment = initFragmentByType(currentOpenedFragment);
        getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.fragment_container, fragment)
            .commit();
        setupDrawerContent(navigationView);
    }
    ...
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(LAST_OPENED_FRAGMENT_REF, currentOpenedFragment);
}

private Fragment initFragmentByType(int type) {
    switch(type) {
        case HOME_FRAGMENT: return new Home();
        case OTHER_FRAGMENT: return new Other();
        default: throw new IllegalArgumentException("There is no type: " + type);
    }
}

And don't forget to update currentOpenedFragment field in onNavigationItemSelected callback.

Michael Spitsin
  • 2,539
  • 2
  • 19
  • 29