Reputation: 6676
I have a PersistFragment which I use to preserve data during MainActivity screen rotations, display of other Activities etc. This works perfectly in most case. I can display other Activities, press the Back button until I get back to my MainActivity etc and it all works fine.
I do have a button on all of these child Activities for jumping straight back to the MainActivity and when I use this, the PersistFragment gets recreated. Why? Whats the difference? How can I stop the PersistFragment from being freed or lost?
Here is the code (MainActivity, onCreate()) which creates the PersistFragment:
super.onCreate( savedInstanceState );
FragmentManager fm = getFragmentManager();
PersistFragment persistFragment = (PersistFragment) fm.findFragmentByTag( TAG_PERSIST_FRAGMENT );
if( persistFragment == null )
{
persistFragment = new PersistFragment();
persistFragment.setRetainInstance( true );
fm.beginTransaction().add( persistFragment, TAG_PERSIST_FRAGMENT ).commit();
System.out.printf( "Created new Fragment!\n" );
}
And here is the onClick handler that takes me all the way back to MainActivity:
public void onClick( View v )
{
Intent intent = new Intent( TVActivity.this, MainActivity.class );
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
}
I see the debug "Created new Fragment!" so it looks as though the PersistFragment has been released somehow.
Upvotes: 0
Views: 699
Reputation: 1026
Try changing persistFragment to savedInstanceState in the if statement
Upvotes: 1