我尝试使用这个重新创建的片段
mFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_frame);
并把它放到新的布局
getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_frame, mFragment ) .commit();
但遇到奇怪的行为:丢失了几个碎片.它们不会更多地显示在屏幕上.在他们的位置是空的.
虽然日志显示片段重新创建正常,但进一步显示片段再次被破坏,再次创建和销毁.
我为展示问题建立了更清晰,没有外壳的测试项目.
并且有明显的结果(插入图片的声誉不够)
Activity started picture
Activity rotated picture
A,B,C,D是片段
正如您在配置更改后看到的那样,一些片段丢失了(B,D)
告诉我我做错了什么
这是帮助的代码(编辑:将代码推送到gitHub以便更容易尝试)
https:// github.com/nailgilaziev/TestFragmentsRetain
p / s抱歉链接
旋转设备后,这里记录猫
MainActivity: onPause Activity MainActivity: onStop Activity MainActivity: onDestroy Activity A: onDestroyview A: onDestroy B: onDestroyview B: onDestroy C: onDestroyview C: onDestroy D: onDestroyview D: onDestroy MainActivity: onCreate Activity A: onCreate B: onCreate C: onCreate D: onCreate MainActivity: replaced MainActivity: onStart Activity A: onCreateView B: onCreateView C: onCreateView D: onCreateView <--before this point all fine and then strange behavior began for the lost fragments(B,D) are performed unnecessary calls--> B: onDestroyview B: onDestroy D: onDestroyview D: onDestroy D: onCreate D: onCreateView MainActivity: onResume Activity通过分解您的问题,使得有两个片段而不是四个,您将看到onCreateView在方向更改时在同一片段上多次被调用.这表明同一片段被添加/创建不止一次.
基本上,当方向更改时,您的Fragments将自动重新附加,因此每次调用onCreate(Bundle)时都不需要执行FragmentTransaction.
你应该在onCreate(Bundle)上做什么呢……
> Null检查传入onCreate(Bundle)的savedInstanceState Bundle. – 如果发生方向更改,则再次调用onCreate(Bundle)并且savedInstanceState Bundle将变为非null. FragmentActivity在重新创建之前将数据保存在onSaveInstanceState(Bundle)中.
>如果savedInstanceState为null,则创建片段并通过FragmentTransaction附加它们.否则,什么也不做.
总之,您修改后的代码应该类似于以下内容……
FragmentManager fm = getSupportFragmentManager(); if(savedInstanceState == null) { fm.beginTransaction() .replace(R.id.a, new A()) .replace(R.id.b, new B()) .replace(R.id.c, new C()) .replace(R.id.d, new D()) .commit(); } else { a = fm.findFragmentById(R.id.a); b = fm.findFragmentById(R.id.b); c = fm.findFragmentById(R.id.c); d = fm.findFragmentById(R.id.d); }
另外,请注意,Fragment的onCreate(Bundle)方法中的savedInstanceState Bundle将始终为null,除非您在onSaveInstanceState(Bundle)中保存了一些内容,因此不要假设saveInstanceState在片段中也是非null的当它被重新创建时,就像FragmentActivity的情况一样.