AndroidViewModel instantiated without passing application context?

后端 未结 2 1045
时光说笑
时光说笑 2021-01-13 13:35

I am currently digging through the Android Room with a View sample app, full source code available here. In this project, an WordViewModel of type Android

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 14:08

    Dependencies

    def lifecycle_version = "2.2.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    kapt "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
    
    implementation "androidx.fragment:fragment-ktx:1.2.4"
    

    Application Class

    class App : Application() {
        //Code
    }
    

    AndroidViewModel Class

    class TestVM (app : android.app.Application) : AndroidViewModel(app){
        // Cast app to the application class
        val myApplication : App = app as App
    }
    

    In Fragment

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val viewModel = ViewModelProvider(this).get(TestVM::class.java)
    }
    

提交回复
热议问题