只是片段与savedInstanceState保存在默认情况下? [英] Are fragments saved by default with savedInstanceState?

查看:245
本文介绍了只是片段与savedInstanceState保存在默认情况下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了什么的onCreate(捆绑savedInstanceState)
这给人的onSaveInstanceState你应用程序的previous状态的包(如果屏幕的方向改变。

I read on What's onCreate(Bundle savedInstanceState) that onsaveinstancestate gives you a bundle of the previous state of the application(if the orientation of the screen changed.

我看着在Android文档( http://developer.android .COM /培训/基础/​​活动的生命周期/ recreating.html ),看到你必须手动将您需要保存为键值对的值。他们的code,这样做是

I looked on the Android docs(http://developer.android.com/training/basics/activity-lifecycle/recreating.html) and saw that you have to manually put the values you want saved as key value pairs. Their code for doing so was

    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);

我的问题是碎片,当方向改变和重建活动他们在自动重新连接?你必须把code将其保存为一个束?
Facebook的继承人code针对这种情况,我想了解

My question is for fragments, are they automatically reattached when the orientation changes and the activity recreated? Would you have to put code to save it into a bundle? Heres facebook code for this situation that I am trying to understand

 @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);
}

}

推荐答案

要保持一个片段,当活动被破坏,所以它会自动reataches,你应该叫

To keep a fragment when an Activity gets destroyed, so it automatically reataches, you should call

Fragment.setRetainInstance(true)

在片段的构造。
没有默认情况下,在保存的onSaveInstanceState()

这篇关于只是片段与savedInstanceState保存在默认情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆