Save instance of dynamically generated views when we switch back and forth between activities

前端 未结 2 513
春和景丽
春和景丽 2020-12-16 07:38

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

2条回答
  •  暖寄归人
    2020-12-16 08:41

    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, 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
    }
    

提交回复
热议问题