Running into a strange issue with `View.generateVi...
# android
g
Running into a strange issue with
View.generateViewId()
here with programatically created Views. It only outputs sequential IDs starting with
1
, and
onRestoreInstanceState
on these Views isn't called at all upon restore. Any ideas?
s
generateViewId
will generate ids which do not collide with generated ID values so I guess sequential IDs starting with
1
don’t collide 🤷 . As for
onRestoreInstanceState
, as I read it, if nothing is saved by
onSavedInstance
state, it won’t be called
The implementation of
generateViewId
:
Copy code
public static int generateViewId() {
        for (;;) {
            final int result = sNextGeneratedId.get();
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }
sNextGeneratedId
being initialised with
Copy code
new AtomicInteger(1)
g
I did save state. I was blaming the generated ID because it seemed so weird compared to the static ones, but you're right, that makes no difference at all.
My problem was that I was creating this View programatically in
Activity.onCreate
, and generating its ID each time, so there was no guarantee that the ID in the saved state would be a match
🤦🏻