【问题标题】:Kotlin viewModels() delegate -> Unresolved Reference [closed]Kotlin viewModels() 委托-> 未解决的参考 [关闭]
【发布时间】: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!")
}

}

The image of the code

当我尝试使用 viewModels 委托时出现此错误。

[<html>Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:<br/>public inline fun &lt;reified VM : ViewModel&gt; Fragment.viewModels(noinline ownerProducer: () -&gt; ViewModelStoreOwner = ..., noinline factoryProducer: (() -&gt; ViewModelProvider.Factory)? = ...): Lazy&lt;TypeVariable(VM)&gt; 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 来达到什么目的?
  • 该死的-_-你说得对,我试图在错误的班级中声明!谢谢。现在它正在工作

标签: android kotlin


【解决方案1】:

问题是由尝试从 ViewModel 类中访问 ViewModel 引起的。

by-delegate 用于从ActivityFragment 访问 ViewModel。 例如,您可以从 Activity 使用此委托。

class MainActivity : AppCompatActivity() {

    private val viewModel: GameViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多