问题
I have an application that has three fragments: Records, Chart, and PieChart. These fragments are stored in a ViewPager in a single activity and the user can swipe between them. 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. 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. 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. Should I be?
回答1:
Going by the example from here:
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. Then in the onActivityCreated() callback, restore the data.
来源:https://stackoverflow.com/questions/17396310/updating-offscreen-fragments-in-a-viewpager