简体   繁体   English

片段轮换不还原当前片段

[英]Fragment Rotation not restoring current fragment

I have a fragmentactivity that starts on Fragment A then can be change to Fragment B. If i am on Fragment B and i rotate my device. 我有一个从fragment A开始的fragmentactivity,然后可以将其更改为FragmentB。如果我在Fragment B上并且旋转设备。 It loads the original Fragment A not Fragment B. I am Loading both Fragment A and B pragmatically. 它加载原始片段A而不是片段B。我正在实用地加载片段A和B。 I thought android was supposed to save which Fragment i was on automatically i am not overriding onSaveInstanceState 我以为android应该自动保存我在哪个片段上,而我不会覆盖onSaveInstanceState

This is how i am loading the fragments 这就是我加载片段的方式

FragmentTransaction t = this.getSupportFragmentManager()
            .beginTransaction();
    t.replace(R.id.fragholder, new MainFragment());
    t.commit();

When you rotate your device, it destroys your Activity and recreates its. 旋转设备时,它会破坏活动并重新创建它。 So assuming Fragment A is the default Fragment, then it is logical that it would load that when the Activity is recreated. 因此,假设片段A是默认片段,那么逻辑上是在重新创建活动时将其加载。 So you would need to override onSaveInstanceState to store which Fragment is visible and then reload that Fragment in onCreate. 因此,您将需要重写onSaveInstanceState来存储可见的片段,然后在onCreate中重新加载该片段。

Reference to relevant Activity Lifecycle doc: http://developer.android.com/training/basics/activity-lifecycle/recreating.html 对相关活动生命周期文档的参考: http : //developer.android.com/training/basics/activity-lifecycle/recreating.html

只需将android:configChanges =“ orientation | screenSize”添加到清单中,android就会为您处理一切

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

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