Wednesday, August 29, 2018

Don't try to store references from within FragmentPagerAdapter.getItem

In my app, I have some activities with tab views managed by FragmentPagerAdapters that need to receive notifications from the containing activity. My first strategy was to store a reference to them in an instance variable on the activity class from within the getItem method, between creating the object and returning it. However, this leads to a crash if the screen is rotated. The activity is recreated, but the fragments don't need to be reinstantiated, so getItem isn't called for the rotated activity and the references remain null.

A better way is to override the instantiateItem method on FragmentPagerAdapter. Calling the superclass's implementation will get or create the fragment object, which can be stored in a reference and then returned.

No comments:

Post a Comment