Persisting list items in ListAdapter on configurationChanges with setRetainInstance

前端 未结 1 891
暗喜
暗喜 2020-12-22 04:19

I have an ArrayListAdapter. On configuration changes the list is not recreated. I would like to persist the list. I have used onSaveInstance() meth

相关标签:
1条回答
  • 2020-12-22 04:52

    I don't understand how the setRetainInstance in Fragment could replace onRetainNonConfigurationInstance for the above situation.

    If your fragment is dynamically added via a FragmentTransaction, and you call setRetainInstance(true) on that fragment, when the device undergoes a configuration change, Android will retain the existing fragment instance and reuse it in the newly-created activity. In all other cases, Android will discard the original fragment and create a brand-new fragment instance to go with the brand-new activity instance. If your fragment instance is retained, all of its data members are retained, so your ListView will be retained, along with its configured ListAdapter and everything else.

    So, the key question is: is the data in your ArrayList part of your data model, or not?

    If it is part of your data model, you probably should be persisting it somewhere (database, JSON file, etc.), and then you can simply reload it in the brand-new fragment instance.

    If it is not part of your data model, then setRetainInstance(true), or possibly onSaveInstanceState(), would be appropriate options.

    0 讨论(0)
提交回复
热议问题