Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

android - Persisting list items in ListAdapter on configurationChanges with setRetainInstance

I have an ArrayListAdapter. On configuration changes the list is not recreated. I would like to persist the list. I have used onSaveInstance() method to do this but I know it is not the best place where to store this kind of data.

A more appropriate method would be onRetainNonConfigurationInstance() but it has been deprecated in favor of setRetainInstance() in a Fragment. I don't understand how the setRetainInstance in Fragment could replace onRetainNonConfigurationInstance for the above situation.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...