2014-05-08 39 views
0

我有一個活動,其中包含一些基於導航抽屜中選定項目交換的片段。我試圖通過調用片段上的setRetainInstance(true)來保留當前片段的方向更改,然後檢查該片段是否存在於onCreate(...)中。然而,當我試圖在onCreate(...)上獲得它時,片段始終爲空。我一直把我的頭撞在桌子上幾個小時。任何人都可以發現問題嗎?片段setRetainInstance(true)不起作用

活動的相關部分

public class StartActivity { 

    private static final String MAIN_FRAGMENT_TAG = "mainFragment"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_start); 

     ... 

     if(savedInstanceState != null) { 
      Fragment f = getSupportFragmentManager().findFragmentByTag(MAIN_FRAGMENT_TAG); 
      if(f == null) { 
       // FRAGMENT IS ALWAYS NULL 
       switchToModeForPosition(...); 
      } else { 
       setupActionBarForPosition(...); 
      } 
     } else { 
      // Default to events view 
      switchToModeForPosition(0); 
     } 
    } 

    private void switchToModeForPosition(int position) { 
     Fragment fragment; 
     switch (position) { 
      default: 
      case 0: //events 
       fragment = new EventsByWeekFragment(); 
       setupActionBarForEvents(); 
       break; 
      case 1: //teams 
       fragment = new AllTeamsListFragment(); 
       setupActionBarForTeams(); 
       break; 
      case 2: //insights 
       fragment = new InsightsFragment(); 
       setupActionBarForInsights(); 
       break; 
      case 3: 
       startActivity(new Intent(this, SettingsActivity.class)); 
       mDrawerLayout.closeDrawer(mDrawerList); 
       return; 
     } 
     fragment.setRetainInstance(true); 
     getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, MAIN_FRAGMENT_TAG).commit(); 
    } 
} 

回答

0

使用setRetainInstance(true)它在每個Fragment類。

public void onCreated(Bundle savedInstanceState) 
     { 
      super.onCreated(savedInstanceState); 
      setRetainInstance(true); 
     } 

或者

public void onActivityCreated(Bundle savedInstanceState) 
    { 
     super.onActivityCreated(savedInstanceState); 
     setRetainInstance(true); 
    } 
+0

對不起,我應該已經發布的代碼了。除了當我在我的活動中構建片段時,我已經這樣做了。 –

相關問題