Reputation: 134
There is my fragment container :
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MapActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentContainer, MainMapFragment.newInstance(), "MainMapFragment");
transaction.commit();
}
Then in the rest of my application I do :
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, NavigationFragment.newInstance());
transaction.addToBackStack("NavigationFragment");
transaction.commit();
All work great if I press back button or my application goes in background then return to it. Fragment A -> Fragment B : back pressed => Fragment A : back pressed => application close.
But if the application is in background and the Android OS killed it to free memory the issue appears :
Fragment A -> Fragment B : back pressed => Fragment A is ON Fragment B (B is always visible on screen) : back pressed => Fragment A (B isn't visible): back pressed => application close.
Anyone has an idea ?
Upvotes: 1
Views: 132
Reputation: 23483
You should check to see if the savedInstanceState
, like so:
if(savedInstanceState == null)
{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragmentContainer, MainMapFragment.newInstance(), "MainMapFragment");
transaction.commit();
}
What happens is that when you put the app into the background, and then come back, you are recreating the fragments, rather than reusing them (which is what you want to do if you are putting the app into the background). This is because the fragments aren't destroyed when you put the app into the background, but when you relauch the app, they are recreated.
Upvotes: 2