简体   繁体   English

在ViewPager中更新屏幕外片段

[英]Updating offscreen fragments in a ViewPager

I have an application that has three fragments: Records, Chart, and PieChart. 我有一个包含三个片段的应用程序:Records,Chart和PieChart。 These fragments are stored in a ViewPager in a single activity and the user can swipe between them. 这些片段在单个活动中存储在ViewPager中,用户可以在它们之间滑动。 The Records fragment has a table where the user can enter data. 记录片段有一个表,用户可以在其中输入数据。 When the user enters data, the other two fragments need to be updated because they reference this data. 用户输入数据时,其他两个片段需要更新,因为它们引用了该数据。 Originally, I wanted the fragments to update as they were swiped to, but since they're swipeable I can't use onPause() and onResume() because onPause() (and thus onResume()) only gets called when a tab is 2+ screens away. 最初,我希望片段在被滑动时进行更新,但是由于它们是可滑动的,因此我无法使用onPause()和onResume(),因为onPause()(因此onResume())仅在制表符为2个屏幕以上。 So I decided to have the Records fragment send a callback to the Activity to tell the other fragments to update themselves when the Records fragment is updated. 因此,我决定让Records片段向Activity发送一个回调,以告诉其他片段在Records片段更新时自行更新。 I keep all the fragments in memory and this works fine until the app goes into the background. 我将所有碎片都保留在内存中,并且在应用程序进入后台之前一切正常。 When the app comes out of the background, if the user enters data into the table, the app crashes because all of the variables in the other fragments are null. 当应用程序退出后台时,如果用户将数据输入表中,则该应用程序将崩溃,因为其他片段中的所有变量均为空。 Why is this happening? 为什么会这样呢? I am not using saveinstancestate anywhere in my app. 我没有在应用程序的任何地方使用saveinstancestate。 Should I be? 我可以做?

Going by the example from here: 从这里开始的例子:

http://developer.android.com/reference/android/app/Fragment.html http://developer.android.com/reference/android/app/Fragment.html

You should save all your data that's backing each of your UI components in the Bundle of your onSaveInstance() of your Fragment. 您应该将支持每个UI组件的所有数据保存在Fragment的onSaveInstance()捆绑包中。 Then in the onActivityCreated() callback, restore the data. 然后在onActivityCreated()回调中,还原数据。

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

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