简体   繁体   English

Android:永久片段被释放了吗?

[英]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. 我有一个PersistFragment,可用于在MainActivity屏幕旋转,其他Activity的显示等过程中保留数据。在大多数情况下,这很完美。 I can display other Activities, press the Back button until I get back to my MainActivity etc and it all works fine. 我可以显示其他活动,按“返回”按钮,直到回到MainActivity等,然后一切正常。

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. 我在所有这些子活动上确实都有一个按钮,可以直接跳回MainActivity,当我使用它时,将重新创建PersistFragment。 Why? 为什么? Whats the difference? 有什么不同? How can I stop the PersistFragment from being freed or lost? 如何阻止PersistFragment释放或丢失?

Here is the code (MainActivity, onCreate()) which creates the PersistFragment: 这是创建PersistFragment的代码(MainActivity,onCreate()):

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: 这里是onClick处理程序,将我带回到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. 因此,似乎PersistFragment已通过某种方式发布。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM