How to prevent custom views from losing state across screen orientation changes

后端 未结 9 1088
时光说笑
时光说笑 2020-11-22 10:11

I\'ve successfully implemented onRetainNonConfigurationInstance() for my main Activity to save and restore certain critical components across screen orientation

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 10:59

    To augment other answers - if you have multiple custom compound views with the same ID and they are all being restored with the state of the last view on a configuration change, all you need to do is tell the view to only dispatch save/restore events to itself by overriding a couple of methods.

    class MyCompoundView : ViewGroup {
    
        ...
    
        override fun dispatchSaveInstanceState(container: SparseArray) {
            dispatchFreezeSelfOnly(container)
        }
    
        override fun dispatchRestoreInstanceState(container: SparseArray) {
            dispatchThawSelfOnly(container)
        }
    }
    

    For an explanation of what is happening and why this works, see this blog post. Basically your compound view's children's view IDs are shared by each compound view and state restoration gets confused. By only dispatching state for the compound view itself, we prevent their children from getting mixed messages from other compound views.

提交回复
热议问题