简体   繁体   中英

Android: Persistent Fragment being freed?

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.

尝试在if语句中将persistentFragment更改为savedInstanceState

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