Member-only story
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
Given that there are 3 Custom Components above, that is of the same view object class. They all inflate the same layout file, that has 3 views, i.e. TextView, EditView and Switch, that has it’s ID. So the IDs are the same across the 3 Custom Components.
Given the mechanism of Saving View State is based on the view’s ID, hence the last component will override all previously saved value. And when it is restored, all the Custom Components will take the same value.
Interesting secret reviewed, isn’t it? Don’t believe try it out yourselves.
So how to solve the problem?
Given this situation, it is risky to rely on the View’s Saved State. Hence it is better to handle the saved-state at the higher level where each ID of the component is different.
As per the design here, that was used to demo the issue, to resolve the problem, the View State should be saved at Custom Component level.