我在What's onCreate(Bundle savedInstanceState)上阅读 onsaveinstancestate为您提供了应用程序之前状态的捆绑(如果屏幕方向发生了变化。
我查看了Android文档(http://developer.android.com/training/basics/activity-lifecycle/recreating.html),发现您必须手动将要保存的值作为键值对。他们这样做的代码是
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
我的问题是片段,当方向发生变化并重新创建活动时,它们会自动重新附加吗?你需要把代码保存到捆绑中吗? 这是我想要了解的情况的Facebook代码
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
答案 0 :(得分:2)
要在活动被销毁时保留一个片段,所以它会自动重新播放,你应该调用
Fragment.setRetainInstance(true)
在Fragment的构造函数中。
默认情况下,onSaveInstanceState()