简体   繁体   English

ViewPager中当前显示的片段的保存状态

[英]Saving state of the currently displayed Fragment in a ViewPager

I'm currently working with a TabLayout that makes use of a ViewPager to display three different instances of a Fragment. 我目前正在使用TabLayout,该TabLayout使用ViewPager来显示Fragment的三个不同实例。 These are the 'master' fragments in my master-detail flow. 这些是我的主从流程中的“主”片段。

When the user rotates the screen, the application will display two fragments, the master and detail fragment. 当用户旋转屏幕时,应用程序将显示两个片段,即主片段和详细片段。 What i've been trying to achieve is to display the same master fragment when rotating from portrait to landscape mode. 我一直试图实现的是从纵向模式转换为横向模式时显示相同的主片段。 So if i'm currently looking at the second instance of 'MyFragment' that lives in the second tab, I want to have that same instance in my master fragment on screen rotation. 因此,如果我当前正在查看位于第二个选项卡中的“ MyFragment”的第二个实例,则希望在屏幕旋转时在我的主片段中具有相同的实例。

I've been looking at different solutions surrounding the Fragment lifecycle but none of them work with my specific scenario. 我一直在寻找有关Fragment生命周期的不同解决方案,但是它们都不适合我的特定情况。 Any advice for this problem would be greatly appreciated! 任何有关此问题的建议将不胜感激!

If the problem isn't clear enough and code is needed, i'll edit this post with the neccessary code. 如果问题还不太清楚,需要代码,我将使用必要的代码进行编辑。

Device re-orientation is a destructive process, as in it destroys the Activity currently shown on screen, and since their lifecycles are tied, any fragments attached to that Activity as well. 设备重新定向是一个破坏性的过程,因为它会破坏当前显示在屏幕上的活动,并且由于它们的生命周期是紧密联系的,因此任何附加到该活动的片段也将被束缚。 To restore the UI state, then what I would do is persist that information as flags/fields in a ViewModel instance. 要恢复UI状态,那么我要做的是将该信息作为标志/字段保留在ViewModel实例中。 So when the device re-orients and the Activity/Fragments are recreated, you can retrieve the VideModel and check it's fields to know which fragment should be shown initially. 因此,当设备重新定位并重新创建“活动/片段”时,您可以检索VideModel并检查其字段以了解最初应显示哪个片段。

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

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