2014-04-01 63 views
0

我有一個導航抽屜,有兩個片段:Fragment0和Fragment1 我想保存方向變化時的狀態。在方向變化時保存片段狀態(savedInstanceState)

這是我的代碼:(只有重要組成部分)

public class MainActivity extends Activity { 

public int selectedPosition = 0; 


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

    if (savedInstanceState == null){ 
     selectItem(0); 
     Log.e("savedInstanceNull", "gets called "+selectedPosition); 
    } else { 
     selectedPosition=savedInstanceState.getInt("fragmentposition",0); 
     Log.v("Position get", ""+selectedPosition); 
     selectItem(selectedPosition); 
    } 

} 

private void selectItem(int position) { 
    // update the main content by replacing fragments 
    Fragment fragment = new PlanetFragment(); 
    Bundle args = new Bundle(); 
    args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
    fragment.setArguments(args); 

    switch(position){ 
    case 0: 
     fragment = new Fragment0(); 
     break; 
    case 1: 
     fragment = new Futtermittelliste(); 
     break; 

    } 

    FragmentManager fragmentManager = getFragmentManager(); 
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); 

    // update selected item and title, then close the drawer 
    mDrawerList.setItemChecked(position, true); 
    setTitle(mPlanetTitles[position]); 
    mDrawerLayout.closeDrawer(mDrawerList); 

    selectedPosition = position; 

} 

@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putInt("fragmentposition", selectedPosition); 
    Log.v("Position saved", ""+selectedPosition); 
} 

}

logcat的:

04-01 18:46:58.455: V/Position saved(2077): 1 
04-01 18:46:58.515: V/Position get(2077): 1 
04-01 18:46:58.555: E/savedInstanceNull(2077): gets called 0 

(1)獲取存儲位置(第一個LogCat輸出) 然後是0在savedInstanceState的被調用,我檢索位置(1)(第二LocCat輸出) 但現在,我不知道爲什麼,在if (savedInstanceState == null)被又一次打來電話,這臺selectItem(0),而不是selectItem(1)

你有一個想法,爲什麼? 在此先感謝!

回答

0

我figuered出來:

if (savedInstanceState != null){ 
     selectedPosition=savedInstanceState.getInt("fragmentposition",0); 
     selectItem(selectedPosition); 
    } else { 
     selectItem(selectedPosition); 
    } 

這工作。我不知道爲什麼第一種方法不起作用,但也許我可以幫助任何人使用此解決方案