I am inflating a view on button click and the user can add as many views as he likes, all is fine I made it work, but now the problem is when I go back one activity and come
As your application may be killed completely at any moment without noticem you have to provide long term storage off heap memory
You only have to restore all the views, if your activity was terminated (and it can be at any time). When it is activated again after termination, it goes through onCreate() method - this would be proper place to restore activity state.
Only callback which is guaranted to be called before your application / activity is destroyed is onPause() - this is a proper place to save views states into long term off-heap storage.
I am thinking that you should implement some kind of logic that helps you restore the state of your Views
. So you should be designing a class, let say ViewDetail
that somehow keeps details about the Views
that you are adding.... type, dimension, etc. This class should implement Parcelable so you are able to add it to the bundle
.
So you will keep an ArrayList<ViewDetail>
, myViews
where everytime the user adds a new View
you create a new ViewDetail
object that you add to your myViews
array.
And then save your Views
and restore them using those objects:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save your view states
outState.putParcelableArrayList("MY_VIEWS",myViews);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get the views back...
myViews=savedInstanceState.getParcelableArrayList("MY_VIEWS");
//TODO: add the views back to your Activity
}