将片段保留在活动生命周期中

时间:2013-08-09 10:01:47

标签: android android-fragments

也许我会想念片段,但我无法理解这种行为:

我有一个包含片段的FrameLayout的Activity。正常情况下,每次我更改方向创建一个新的FrameLayout实例时,活动都会被销毁。但是我不希望再次创建片段,我想保留相同的片段实例,因为它需要大量的时间来加载。

我正在做的是以下(假设FrameLayout的id = 324):

    FragmentManager mng = getFragmentManager();
    Fragment frag = (Fragment)mng.findFragmentByTag(DEFAULT_TAG);

    //I create a new fragment if it doesn't exist or I remove the fragment from any view that is attached if it existed
    if (frag==null) frag = new MyFragment();
    else mng.beginTransaction().remove(frag).commit();

    //I add the fragment to the newly created FrameLayout
    mng.beginTransaction().add(324, frag, DEFAULT_TAG).commit();

它崩溃了:

08-09 11:54:38.970: E/AndroidRuntime(2517): Caused by: java.lang.IllegalArgumentException: Binary XML file line #15: Duplicate id 0x7f050016, tag null, or parent id 0xffffffff with another fragment for com.test.PRMapFragment
08-09 11:54:38.970: E/AndroidRuntime(2517):     at android.app.Activity.onCreateView(Activity.java:4248)

第一次一切正常,但是当旋转屏幕时,它会崩溃。它抱怨MyFragment中的一个片段,但没有任何意义,因为片段没有改变。

1 个答案:

答案 0 :(得分:2)

查看Fragment.setRetainInstance()http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)

如果将其设置为true,它会更改片段生命周期,以便它不会被破坏并与活动一起重新创建,而只是分离并重新附加到新活动。它挂钩到活动的onRetainNonConfigurationInstance()回调,以使对象在配置更改之间保持活动状态。

我已经多次使用不可见的片段,以允许长时间运行的操作跨配置更改工作。我没有在带有视图的可见片段中尝试过它,但是要小心你应该能够使用它。