Android - Restore dynamically added view state on orientation change

438 Views Asked by At

Im currently working with custom views which will be added to a layout dynamically. I understand how view states are safed and restored.

According to the documentation, only views with an id will be persisted by the system. So the suggested solution is to use View.getViewId() in order to set an id to each dynamically added view.

The problem is, that on orientation change, each view which gets an id via this method, will get a different id than before the orientation change happened. This prevents the view state from being restored since the ids don't match up.

Easiest setup to try this: Add an EditText programmatically to an activity, give it an id with View.generateViewId() then enter some text and rotate.

Am I missing something? Is there no way to give ids to dynamically added views so that they restore themselves on orientation changes?

1

There are 1 best solutions below

2
On

When you create the ID via generateViewId(), you must also hold onto that generated ID as a variable in your Activity/Fragment, manually saving the ID via onSaveInstanceState() and then later restoring that saved ID by looking at the savedInstanceState parameter.

By doing this, you ensure that you only generate an ID exactly once, thus ensuring that you use the same ID for every subsequent recreation and therefore have your state restored properly.