简体   繁体   中英

Fragments and android life cycle

I've got something strange with my android app.

If I run main activity and then go through few fragments, I'll see main activity after hiding/unhiding the app. If I press "back", it will show the fragment that was shown right before hiding. But sometimes app shows me the last fragment after unhiding. How can I make my app show the last fragment everytime if it's possible? Or how can I make my app save its state?

If I understand, you want when the "back" button is pressed, the last fragment should be displayed. For this you can depend on the addToBackStack method to handle the Back press. From Google code snippet @ Fragments :

Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Note: In this case newFragment is your last fragment.

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