I am trying to implement ViewModel in a 100% Kotlin app. Every piece of documentation I can find says I want to use this to get the ViewModel instance:

ViewModelProviders.of(this).get(CustomViewModel::class.java)

根据文档,我应该可以通过以下方式导入此文件:

import android.arch.lifecycle.ViewModelProviders

This import is unresolved though. I am using the following in my build file:

def androidArchVersion = '1.1.1'
implementation "android.arch.lifecycle:viewmodel:$androidArchVersion"
implementation "android.arch.lifecycle:livedata:$androidArchVersion"
annotationProcessor "android.arch.lifecycler:compiler:$androidArchVersion"
testImplementation "android.arch.core:core-testing:$androidArchVersion"

Why can't I access ViewModelProviders?

推荐答案

Include the following as a dependency:

implementation "android.arch.lifecycle:extensions:1.1.1"

The equivalent AndroidX dependency is:

"androidx.lifecycle:lifecycle-extensions:VERSION"

在这里,版本可以替换为当前稳定的,Beta或Alpha值为in this official link

这种依赖关系既适用于ViewModel,也适用于LiveData,因此不需要为同一个对象提供单独的依赖关系;i、 e.您指出的前两个依赖项可以由前面提到的生命周期扩展依赖项替换.

Kotlin相关问答推荐

如何创建继承抽象的匿名对象的新实例?

在Kotlin中可以连接两个范围吗?

Regex(Kotlin)仅匹配句子末尾的句号,而忽略中间的句号,如缩写

jOOQ Kotlin Coroutines - Select all and exists查询

CompositionLocal 究竟如何以及何时隐式设置值?

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

为什么这两个 Kotlin 协程函数不一样?

在子类中覆盖 kotlin 运算符扩展函数

为什么 Kotlin 在 sumOf 函数 lambda 中默认不将数字视为Int?

为什么 Kotlin 的 null 安全性不能与局部变量初始化器一起正常工作?

将子元素放在一个列表中

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

如何使用 Android CameraX 自动对焦

Swift vs Kotlin 在排序数组上的表现

致命错误 LifecycleOwners 必须在 registerForActivityResult 开始之前调用 register

将 jetpack compose 添加到现有元素

Kotlin Compose,在行中对齐元素

如何使用 Kotlin Coroutines 使 setOnClickListener debounce 1 秒?

Android Kotlin StringRes 数量String

如何在Kotlin中创建无限长的序列