Tony
Tony

Reputation: 3805

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?

Upvotes: 0

Views: 49

Answers (1)

The Original Android
The Original Android

Reputation: 6215

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.

Upvotes: 1

Related Questions