当你的方向改变时,你的Activity
被重新创建。
"In the scenario where a user rotates their device, Android will destroy your
application’s activity(s). Before destroying them it calls, onSaveInstanceState,
allowing developers to persist data. Once the activity is recreated post
rotation, the OS will call onRestoreInstanceState giving developers a chance to
restore the application state pre-rotation."
你应该尽力挽救你的Fragments State
.
放置片段: 将对片段的引用放入 Bundle 中。该 Bundle 可以持久保存为已保存状态,并且稍后恢复 getFragment(Bundle, String) 时将返回同一片段的当前实例。
@Override
protected void onSaveInstanceState(Bundle outState) {
FragmentManager manager = getFragmentManager();
manager.putFragment(outState, MyFragment.TAG, mMyFragment);
}
获取片段: 检索先前使用 putFragment(Bundle, String, Fragment) 放置的引用的当前 Fragment 实例。
private void instantiateFragments(Bundle inState) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
if (inState != null) {
mMyFragment = (MyFragment) manager.getFragment(inState, MyFragment.TAG);
} else {
mMyFragment = new MyFragment();
transaction.add(R.id.fragment, mMyFragment, MyFragment.TAG);
transaction.commit();
}
}
恢复片段:
@Override
protected void onRestoreInstanceState(Bundle inState) {
instantiateFragments(inState);
}
希望这可以帮助。