2013-04-02 26 views
1

我有一個包含一個片段的佈局:片段與retainInstance =真,但的onCreate稱爲

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/root" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <fragment 
     android:id="@+id/ID" 
     class="com.teovald.app.MyFragment" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 

    <include 
     android:id="@+id/toolbar" 
     layout="@layout/toolbar" /> 

</FrameLayout> 

我設置在該片段onCreate方法此使用setRetainInstance(真):

public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setRetainInstance(true); 
    ....} 

而最後,我恢復了在其活動onCreate中對此片段的引用:

public void onCreate(Bundle icicle) { 
    super.onCreate(icicle); 
    setContentView(R.layout.main); 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    mFragment = (MyFragment) fragmentManager.findFragmentById(R.id.ID);  
    ... 
} 

但是,每次我旋轉我的設備時,都會調用onCreate,然後調用片段的onCreate!由於我將setRetainInstance設置爲true,因此不應該發生。 是否有這種行爲的原因?

+1

它可能有一些做的生命週期以及事情是如何從XML膨脹......你可能會考慮做'FragmentManager fragmentManager = getSupportFragmentManager(); mFragment =(MyFragment)fragmentManager.findFragmentById(R.id.ID);'ononStart()'或'onResume'代替... – JRaymond

+0

感謝您的建議。只留下super.onCreate&setContentView雖然沒有幫助。不要用最後的框架庫替換ActionBarSherlock和兼容性庫。它一定是別的,但我開始用盡選項: - / – Teovald

回答

2

我最近有這個問題,並與它鬥爭了幾個小時,直到我發現在Activity中包含保留的non-ui-fragment在onSaveInstanceState中的代碼(我從一些第三方庫中複製)還有就是super.onSaveInstanceState()

沒有呼叫這就像:

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    // Save the mapview state in a separate bundle parameter 
    final Bundle mapviewState = new Bundle(); 
    mMapFragment.onSaveInstanceState(mapviewState); 
    outState.putBundle(BUNDLE_STATE_MAPVIEW, mapviewState); 
} 

所以我加入了未接來電是這樣的:

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    // Save the mapview state in a separate bundle parameter 
    final Bundle mapviewState = new Bundle(); 
    mMapFragment.onSaveInstanceState(mapviewState); 
    outState.putBundle(BUNDLE_STATE_MAPVIEW, mapviewState); 
} 

現在onCreate()不會在保留的片段中調用兩次。

我希望這會幫助別人:)

相關問題