A must know secret about Android View State storing mechanism!

Saving and Restoring view state is so common, that it’s unbelievable this is not known to me till now. Missing this bit might cause some bizarre behavior.

Demonstration of issue

I’m taking the CustomComponent example from https://medium.com/@elye.project/building-custom-component-with-kotlin-fc082678b080 to illustrate the issue.

Check out the gif below. Don’t Keep Activity (i.e. when you background the App and foreground it, a new Activity is recreated) is ON.

There are 3 components, that doesn’t interact with each other. However, upon background and foreground, component 1 and 2 will always take the value of component 3. Both time in the GIF below shows the behavior. Why!? Bug!?

Why is this happening?

The simple reason is this… a secret that must be known…

Android View’s state is saved based on the ID of the View

Explanation

--

--