多个片段,setRetainInstance(真)和屏幕旋转多个、片段、屏幕、setRetainInstance

2023-09-05 10:54:32 作者:血染墨冢

我在多个片段之间通过更换开关。该片段也被添加到背叠

I'm switching between multiple fragments via replace. The fragments are also added to the back stack.

现在我想上的方向变化的碎片不会再创建。我把 setRetainInstance(真)在他们每个人。

Now I want that on orientation change the fragments aren't created again. I put setRetainInstance(true) on each of them.

片段A的行为确定。然后我切换到B片段,旋转屏幕,看到片段A.我究竟做错了什么?抑或是这正常吗?

Fragment A behaves ok. Then I switch to fragment B, rotate the screen and see fragment A. What am I doing wrong? Or is this expected?

推荐答案

调用 setRetainInstance(真)以片段不摧毁和重建本身停止你的活动。也许你初始化第一个片段在的onCreate 方式,所以它与你的第一个片段按预期工作,但不与第二个。你要么需要存储哪些片段是用的onSaveInstanceState 方式在您的活动显示,并显示相应之一OnCreate中,或者你需要设置你的活动标志为安卓configChanges =keyboardHidden |方向|屏幕大小以保持它destroyng屏幕上的方向变化

Calling setRetainInstance(true) to fragment doesn't stop your activity from destroying and recreating itself. Probably you initialize the first fragment in your onCreate method, so it works with your first fragment as expected, but not with the second one. You either need to store which fragment is shown using onSaveInstanceState method in your activity and show the corresponding one in OnCreate, or you need to set your activity flags to android:configChanges="keyboardHidden|orientation|screenSize" to keep it from destroyng on screen orientation change.