简体   繁体   English

片段重新配置更改

[英]Fragment recreation on configuration change

I have a doubt on configuration change handling by os, Lets say I have an Activity inside its onCreate() it is creating one (or more) fragment instance using a special constructor defined in that fragment. 我对os的配置更改处理有疑问,假设我在onCreate()中有一个Activity,它使用该片段中定义的特殊构造函数创建一个(或多个)片段实例。

When device orientation changes system will destroy and create the fragment again, if I am correct it will use default (no argument) constructor to do that, meanwhile the activity is also getting recreated and it will again instantiate fragment using same constructor. 当设备方向改变时,系统会破坏并再次创建片段,如果我是正确的,它将使用默认(无参数)构造函数来执行此操作,同时活动也将重新创建,它将再次使用相同的构造函数实例化片段。 My question is, will there be two different instances in the memory? 我的问题是,内存中会有两个不同的实例吗? if not, how they are resolved and become one? 如果没有,他们如何解决并成为一个?

Some background 一些背景

The responsibility to keep the state of a fragment throughout the life of the activity is on the FragmentManager , this is why there is an option to commit and to commitAllowingStateLoss when committing a fragment transaction. 在活动的整个生命周期中保持片段状态的责任在FragmentManager ,这就是为什么在提交片段事务时有commitcommitAllowingStateLoss的选项。 If left to it's own devices the Fragment 's state will be restored automatically. 如果留给它自己的设备, Fragment的状态将自动恢复。 But... if you add the fragment in code (as opposed to adding it in the xml layout) then it is up to you to add it only when needed. 但是......如果你在代码中添加片段(而不是在xml布局中添加它),那么只有在需要时才能添加它。
Usually, in the case of onCreate it is enough to check that the activity is not being restarted, that is, check that savedInstanceState == null and only then add the fragment. 通常,在onCreate的情况下,检查活动是否未重新启动就足够了,即检查savedInstanceState == null然后再添加片段。

Take a look at this snippet from the fragment's guide: 从片段指南看一下这个片段:

public static class DetailsActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getResources().getConfiguration().orientation
            == Configuration.ORIENTATION_LANDSCAPE) {
        // If the screen is now in landscape mode, we can show the
        // dialog in-line with the list so we don't need this activity.
        finish();
        return;
    }

    if (savedInstanceState == null) {
        // During initial setup, plug in the details fragment.
        DetailsFragment details = new DetailsFragment();
        details.setArguments(getIntent().getExtras());
        getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
    }
}

} }

PS PS

The answer to your question: 你的问题的答案:

will there be two different instances in the memory? 内存中会有两个不同的实例吗?

Yes, if you just add the fragment on each call to onCreate there will be more than one instance. 是的,如果您只是在每次调用onCreate添加片段,那么将会有多个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM