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

后端 未结 9 1049
时光说笑
时光说笑 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:58

    Easy with kotlin

    @Parcelize
    class MyState(val superSaveState: Parcelable?, val loading: Boolean) : View.BaseSavedState(superSaveState), Parcelable
    
    
    class MyView : View {
    
        var loading: Boolean = false
    
        override fun onSaveInstanceState(): Parcelable? {
            val superState = super.onSaveInstanceState()
            return MyState(superState, loading)
        }
    
        override fun onRestoreInstanceState(state: Parcelable?) {
            val myState = state as? MyState
            super.onRestoreInstanceState(myState?.superSaveState)
    
            loading = myState?.loading ?: false
            //redraw
        }
    }
    

提交回复
热议问题