I implemented an activity with a navigation drawer and a content fragment. The content fragment is replaced many times. But at some point I must provide a jumpback to a specific fragment with a specific state. I managed to save any required variables. And it works often but not always to jump back.
I make a button in the actionbar visible if the specific fragment calls their onPause()
method. But, since the life cycle of a fragment is tied to the activity's and the activity is not changing, sometimes the button does not appear because onPause()
is not called.
So: Which method is always triggered if a fragment is not anymore in foreground?
I tried: onPause
, onStop
, onHiddenChanged()
....
Update:
Here is my code to save the game state, which is placed in the fragment. Until now it is placed in the onStop()
method. The gamelogic variable is an object with many many values and collections. I save this to the shared preferences.
@Override
public void onStop() {
super.onStop();
if(!isGameDone){
SharedPfref sharedPfref = new SharedPfref();
sharedPfref.saveGameLogicInSharedPref(this.gameLogic);
} else {
SharedPfref sharedPfref = new SharedPfref();
sharedPfref.deleteGameLogicFromSharedPref();
}
}
In my main activity I decide to display an icon at the action bar or not. By a press on this button I restart the fragment with the saved game state holder.
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
SharedPfref sharedPfref = new SharedPfref();
if(sharedPfref.isGameLogicSavedInSharedPref()){
menu.findItem(R.id.action_resume_game).setVisible(true);
} else {
menu.findItem(R.id.action_resume_game).setVisible(false);
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch(item.getItemId()) {
case R.id.action_resume_game:
SharedPfref sharedPfref = new SharedPfref();
GameLogic gameLogic = sharedPfref.loadGameLogicFromSharedPref();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, GameFragment.newInstance(gameLogic))
.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}