0

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?

Tine
  • 1
  • 1

1 Answers1

2

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.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • I thought about sth like that. But how would I remember which id was generated for which view!? In my case: I have a json file which represents a type of checklists, and I build my views dynamically by parsing that json. So in the end I have a customview (checklist view) which contains 1..* custom views (checkboxes,edittexts,etc). How would I remember which view had which id? – Tine Sep 29 '20 at 06:29
  • Yep, you'll need to keep track of every ID separately. `onSaveInstanceState()` supports arrays as well as complex `Parcelable` implementations so it really up to you to build out as complicated of a structure as you need to keep track of IDs. – ianhanniballake Sep 29 '20 at 15:23