2013-06-26 41 views
5

我以为我明白你应该在onDestroy()中的onCreate()和FragmentTransaction.remove()中调用FragmentTransaction.add()。在我的onDestroy应用程序崩溃()与此错误:Android:什么时候使用FragmentTransaction.remove是否合适?

06-26 15:25:50.213: E/AndroidRuntime(579): java.lang.RuntimeException: Unable to destroy activity {com.myapp/com.myapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed 

我什么时候把这些东西如果不是的onCreate /的onDestroy()?

+3

当活动被破坏时,您不需要手动销毁碎片 - 碎片框架为您管理碎片。 – CommonsWare

+0

好的。我在网上搜索解决方案时已经阅读过。我的问题是,当我切换到我的水平视图,然后回到我的垂直视图,我现在至少有一个嵌套片段的重复布局。在顶部有一个用于该片段的布局,它不会从setText获取更新,然后是该布局下方的另一个副本,它会从setText获取更新。 – KairisCharm

回答

3

My problem with that is that when I switch to my horizontal view, and then back to my vertical view, I now have a duplicate layout for at least one of the nested fragments.

我猜测是,这是因为你总是加入片段中onCreate()。 Android会根据配置更改自动重新创建片段。因此,onCreate()应检查是否片段添加它之前已经存在:

@Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null) { 
     getSupportFragmentManager().beginTransaction() 
           .add(android.R.id.content, 
             new RotationFragment()).commit(); 
    } 
    } 
+0

你可能是对的。但是当我做 if(getChildFragmentManager()。findFragmentByTag(“MyFrag”)== null) 我总是得到一个返回true。 – KairisCharm

2

好了,你的解决方案工作,只是不使用:

if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null) 

我用:

if (savedInstanceState==null) 

显然片段管理器不是由onCreate函数设置的。但是,由于你的答案大部分是正确的,我将其标记为答案。

我想再次感谢你。这是你第二次对我有很大的帮助,我非常感激。

相关问题