android save programmatically created views

梦想与她 提交于 2019-12-20 03:46:15

问题


I programmatically create a RelativeLayout with some other views inside it and add it to the parent which is defined in XML. But all the views (incl. the layout) that were created programmatically disappear after the activity is re-created. Do I need a SharedPreferences object to save the values and then re-create the layout or is there an easier way to save it?

P.S. all new created views get an id assigned


回答1:


Do I need a SharedPreferences object to save the values and then re-create the layout

You say that you are creating these widgets in onResume(). Your code in onResume() needs to know what widgets need to be created. If this is purely transient information, and you are worried about things like the activity being destroyed and re-created due to a screen rotation or other configuration change, use onSaveInstanceState() on the activity or fragment to pass data about these widgets from the old to the new instance of the activity. If, on the other hand, you are worried about being able to re-create these views several months later, you need to store this information persistently: SharedPreferences, database, some other file structure, "the cloud", etc.




回答2:


I recommend you look into Activity.onSaveInstanceState(Bundle):

The default implementation takes care of most of the UI per-instance state for you by calling onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState()). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation [ via super.onSaveInstanceState() and super.onRestoreInstanceState()], otherwise be prepared to save all of the state of each view yourself.

https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

as well as my answer here:

How can I assign an ID to a view programmatically?



来源:https://stackoverflow.com/questions/14033619/android-save-programmatically-created-views

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