简体   繁体   中英

Retain fragment state in activity

I have an activity let's say its name is MainActivity , there are three button in that activity,

button one launch FragmetA
button two launch FragmetB
button three launch FragmetC

when the MainActivity launch initially FragmentA launch.

Lets say there is a button in FragmentB , on that button click a new Activity SecondActivity launch . When I click the backbutton from SecondActivity , it backs to MainActivity and FragmentA launch, what I want is when I will press the back button from SecondActivity I want to see FragmentB , how can I do this ?

Just save which fragment was opened in onSaveInstanceState , and show proper fragment in onCreate . For instance:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState != null) {
        switch (savedInstanceState.getString("fragment")) {
            case "a":
                //show fragment a
                break;
            case "b":
                //show fragment b
                break;
            ...
        }
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putString("fragment", "a"); // in case if fragment a visible
}

when the MainActivity launch initially FragmentA launch.

How do you launch your fragment from MainActivity ? Your Fragment state should be persisted by the FragmentManager , so if you do:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        // Only launch if Activity is not recreated.
        launchFragmentA();
    }
}

You should see SecondActivity when returning from FragmentB .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM