Saving State in a Compound Control

If you’re writing an android compound control and you want to save state between config changes, you may want to tell the Android SDK to butt out.

That is, you may want your compound control to be fully in charge of saving and restoring the states of its internal views.

Why would you want to do that – why not just let the Android SDK save and restore those interior view states?

Because in order to correctly save the states of those interior views, the Android SDK needs each of them to have unique ids.

And when does that become problematic?

When a client of your compound control puts multiple instances of it into a single one of their layouts. In this case, the interior views will all get the same ids or no ids at all. (Unless you want to deal with a certain amount of awkwardness in code.)

So, if, for example, your compound control consists of a LinearLayout which wraps some other stock views, it can be desirable for your LinearLayout to tell Android to simply avoid saving the states of those interior views. You can do this by calling dispatchFreezeSelfOnly and dispatchThawSelfOnly.

A helpful example of this is Charles Harley’s Lock Combination Picker on GitHub.

A discussion about how BaseSavedState should be used to save the state of your compound view is found in this StackOverflow question.

Written on February 18, 2015