Nick
Nick

Reputation: 6385

Fragment not readded on restart

I have an Activity that manages about four fragments. The activity decides when to add/replace/hide/show certain fragments. When my application is closed (due to low memory) and then reopened by the user, the fragments are not automatically readded to the fragment manager. How can I save the which fragments are added so that when the application is restarted the user will be brought to the same page they were on previously?

I assume use onSaveInstanceState() but I'm not sure exactly what to save...

Thanks

Upvotes: 0

Views: 613

Answers (1)

RobGThai
RobGThai

Reputation: 5969

One thing I do is keeping track of the displayed screen as integer. Activity will hold a private int with current screen as its value.

private int currentScreen = -1;
private static final int SCREEN_MENU = 0;
private static final int SCREEN_PROFILE = 1;
private static final int SCREEN_HELP = 2;

private void switchToMenu(){
    currentScreen = SCREEN_MENU;
    //Load Fragment into frame.
}

private void switchToProfile(){
    currentScreen = SCREEN_PROFILE;
    //Load Fragment into frame.
}

private void switchToHelp(){
    currentScreen = SCREEN_HELP;
    //Load Fragment into frame.
}

@Override
public void onResume(){
    switch(currentScreen){
    case SCREEN_MENU: switchToMenu(); break;
    case SCREEN_PROFILE: switchToProfile(); break;
    case SCREEN_HELP: switchToHelp(); break;
    }
}

This method won't save everything on the screen as I only want to track the current page being displayed hence I only care about currentScreen. But you should get an idea anyway.

:)

Upvotes: 1

Related Questions