Updating offscreen fragments in a ViewPager

混江龙づ霸主 提交于 2019-12-24 13:31:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!