【发布时间】:2021-09-29 16:40:15
【问题描述】:
我目前正在 developer.android.com 上学习 Kotlin
代码如下:
class GameViewModel : ViewModel() {
init {
Log.d("GameFragment", "GameViewModel created!")
}
private val viewModel: GameViewModel by viewModels()
private var score = 0
private var currentWordCount = 0
private var _currentScrambledWord = "test"
public val currentScrambledWord: String
get() = _currentScrambledWord
override fun onCleared() {
super.onCleared()
Log.d("GameFragment", "GameViewModel destroyed!")
}
}
当我尝试使用 viewModels 委托时出现此错误。
[<html>Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:<br/>public inline fun <reified VM : ViewModel> Fragment.viewModels(noinline ownerProducer: () -> ViewModelStoreOwner = ..., noinline factoryProducer: (() -> ViewModelProvider.Factory)? = ...): Lazy<TypeVariable(VM)> defined in androidx.fragment.app]
这是我的配置:
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
// LiveData
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
// ViewModel
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.fragment:fragment-ktx:1.3.6'
implementation 'androidx.activity:activity-ktx:1.3.1'
我找到了这篇文章:'by viewModels()' Kotlin property delegate unresolved reference
但这并不能解决我的错误。
有人可以帮帮我吗?
【问题讨论】:
-
此委托仅适用于片段和活动。你想通过在
GameViewModel中引用GameViewModel来达到什么目的? -
该死的-_-你说得对,我试图在错误的班级中声明!谢谢。现在它正在工作