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

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

问题描述

我阅读了什么是onCreate(Bundle savedInstanceState)
onsaveinstancestate为您提供捆绑以前的应用程序状态(如果屏幕的方向改变了。

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/training/basics/activity-lifecycle/recreating.html ),并看到您必须手动将要保存的值作为键值对,他们的代码是

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

我的问题是片段,当方向更改和活动重新创建时,是否自动重新连接?你要把代码保存成捆绑包吗?
对于我想要了解的这种情况,对于这种情况来说,这是一个Facebook代码。

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

}

推荐答案

为了在活动被破坏时保留一个片段,所以它会自动重新绘制,你应该调用

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

Fragment.setRetainInstance(true)


默认情况下, onSaveInstanceState()

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

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