The android developers guide says that Views
in your activity need to have unique ids in order to restore them in onRestoreInstanceState()
. This is because onRestoreInstanceState()
works by making a SparseArray
with ids as keys.
I find this extremely strange because so many standard Android approaches encourage reuse of ids. For example, all of the constructors for an ArrayAdapter
take a resourceId as parameter, so that the same xml resource is inflated for all children in a ListView
. Similarly if you use <include layout ...>
in your xml, you are reusing view ids.
So unless developers aren't actually using the the standard, recommended, approaches I can't see that there are many apps out there actually meeting the requirement that all Views
have unique ids.
Is this conclusion wrong? Also, what is the behaviour of onRestoreInstanceState
if the ids are not all different, and is this behaviour acceptable?
EDIT
The relevant quotes appear on the page http://developer.android.com/training/basics/activity-lifecycle/recreating.html and read as follows:
Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
Caution: Always call the superclass implementation of onRestoreInstanceState() so the default implementation can restore the state of the view hierarchy.
AdapterView
(the base class for allViewGroup
s that utilize anAdapter
) is implemented so as to not save or restore the state of it's childView
s, as that is the domain of theAdapter
and should be handled at that level.As for the case of a sublayout that is statically included at multiple points, if it has any state to be saved then you will need to either assign unique ids to all stateful
View
s, or manage the state manually from theActivity
orFragment
.Unfortunately, the ids need to be unique across the whole
View
structure, instead of just among it's siblings. This is due to the fact that the state of the whole structure is saved inside one single-dimensionalSpareArray
. Thus if there are multiple statefulView
s in the structure sharing the same id, then only the state of the last one in the structure will be saved, and it will be applied to all theView
s with that id upon state restoration.