Fragment Field is NULL after rotate device in Android

后端 未结 4 898
攒了一身酷
攒了一身酷 2021-01-23 11:39

When I start the app everything works ok but when I rotate to landscape it crashes because in the Fragment there is a field that is NULL.

I don

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 12:31

    The main problem I see with your app is your misunderstanding with how FragmentPagerAdapter works. I see this a lot and it's due to lack of good javadocs on the class. The adapter should be implemented so that getItem(position) returns a new fragment instance when called. And then getItem(position) will only be called by the pager when it needs a new instance for that position. You should not pre-create the fragments and pass then into the adapter. You should also not be holding strong references to the fragments from either your activity or from parent fragments (like ParentBasicInfoFragment). Because remember, the fragment manager is managing fragments and you are also managing fragments by newing them and keeping references to them. This is causing a conflict and after rotation, you are trying to invoke activityNotifiDataChange() on a fragment that is not actually initialized (onCreate() was not called). Using the debugger and tracking object IDs will confirm this.

    If you change your code so that the FragmentPagerAdapter creates the fragments when they are needed and don't store references to fragments or lists of fragments, you will see much better results.

提交回复
热议问题