在方向更改上保存Fragment的状态(savedInstanceState)

时间:2014-04-01 16:54:05

标签: java android android-fragments

我有一个带有两个片段的导航抽屉:Fragment0和Fragment1 我想在改变方向上保存状态。

这是我的代码: (只有重要部分)

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输出) 然后调用else statement的{​​{1}}并检索位置(1)(第二个LocCat输出) 但是现在,我不知道为什么,savedInstanceState再次被调用,这会设置if (savedInstanceState == null)而不是selectItem(0)

你知道为什么吗? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

我明白了:

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

这很有效。我不知道为什么第一种方法不起作用,但也许我可以帮助任何人解决这个问题