app/build.gradle
引入 Dependencydependencies {
...
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1'
...
}
HomeViewModel
為例)ViewModel
init {}
:初始化內容class HomeViewModel: ViewModel() {
...
init {
...
}
}
class HomeAndroidViewModel(val context: Application) : AndroidViewModel(context) {
...
}
private val homeViewModel: HomeViewModel by viewModels()
時間點 | 旋轉螢幕前 | 旋轉螢幕 | 旋轉螢幕後 |
---|---|---|---|
Activity | MainActivity[實體A] | - | MainActivity[新的實體B] |
兩者Pair與否 | v | x | v |
ViewModel | HomeViewModel[實體1] | HomeViewModel[實體1] | HomeViewModel[實體1] |