2012-12-06 8 views

回答

5

您應該重寫onSaveInstanceState並保存選定的導航列表中的位置捆綁。 不要忘記恢復在onCreate的位置。

請看下面的例子:

public class MainActivity 
{ 

    private static final String CURRENT_FRAGMENT_TAG = "fragmentPosition"; 

    @Inject @Named("navigationFragments") 
    private Provider<? extends Fragment>[] fragmentProviders; 

    @Override 
    protected void onCreate(Bundle bundle) 
    { 
     super.onCreate(bundle); 

     final ActionBar actionBar = getSupportActionBar(); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); 
     actionBar.setListNavigationCallbacks(ArrayAdapter.createFromResource(
      this, R.array.navigation_menu, android.R.layout.simple_list_item_1), new ActionBar.OnNavigationListener() 
     { 
      @Override 
      public boolean onNavigationItemSelected(int itemPosition, long itemId) 
      { 
       final String fragmentTag = "fragment-" + itemPosition; 

       // to prevent fragment re-selection and loosing early saved state 
       if (getSupportFragmentManager().findFragmentByTag(fragmentTag) != null) 
       { 
        return true; 
       } 

       final Fragment fragment = fragmentProviders[itemPosition].get(); 
       getSupportFragmentManager().beginTransaction(). 
        replace(android.R.id.content, fragment, fragmentTag). 
        commit(); 
       return true; 
      } 
     }); 
     actionBar.setSelectedNavigationItem(bundle != null 
      ? bundle.getInt(CURRENT_FRAGMENT_TAG) 
      : 0); 
    } 

    @Override 
    protected void onSaveInstanceState(Bundle outState) 
    { 
     super.onSaveInstanceState(outState); 
     outState.putInt(CURRENT_FRAGMENT_TAG, getSupportActionBar().getSelectedNavigationIndex()); 
    } 

    /* 

     Additional stuff here 

    */ 

} 

Provider<? extends Fragment>[] fragmentProviders是創造了新的片段工廠方法的對象的列表。 更換getSupportActionBar()getActionBar()getSupportFragmentManager()getFragmentManager(),如果你不使用actionbarsherlock

+0

謝謝您的回答,這是我找到的最好的辦法。 –

+0

我認爲actionBar.setSelectedNavigationItem行正在對Asynctaskloader進行另一次調用。如何超過這個。 –

相關問題