【问题标题】:Keep getting a "Classifier 'SharedViewModel' does not have a companion object, and thus must be initialized here" error when using a view model使用视图模型时不断收到“分类器‘SharedViewModel’没有伴随对象,因此必须在此处初始化”错误
【发布时间】:2021-01-05 18:09:21
【问题描述】:

我的代码中有两个错误。一个是在私有 val sharedView 模型中,我不断收到“分类器 'SharedViewModel' 没有伴随对象,因此必须在此处初始化”。最后,在 question.text = sharedViewmodel.question 和 question.text = sharedViewModel.answer 这两行中,我都得到“类型不匹配。 必需的: 可编辑! 成立: 字符串?”但是当我尝试将其更改为可编辑时,我会在问题/answer.text.toString() 的按钮单击侦听器下方收到错误。有谁知道如何解决这些问题?这是我的代码:

    package com.example.quest

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import com.google.android.material.floatingactionbutton.FloatingActionButton

class SecondActivity : AppCompatActivity() {
    private val sharedViewModel: SharedViewModel by viewModels(SharedViewModel)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        val question = findViewById<EditText>(R.id.question)
        val answer = findViewById<EditText>(R.id.answer)

        if(sharedViewModel.question != null) {
            question.text = sharedViewModel.question
        }

        if(sharedViewModel.answer != null) {
            answer.text = sharedViewModel.answer
        }

        findViewById<FloatingActionButton>(R.id.btn3).setOnClickListener {

            sharedViewModel.question = question.text.toString()
            sharedViewModel.answer = answer.text.toString()
            val questiontext = question.text.toString()
            val answertext = answer.text.toString()

            val returnIntent = Intent()
            returnIntent.putExtra("test", questiontext)
            returnIntent.putExtra("test2", answertext)
            setResult(Activity.RESULT_OK, returnIntent)

            finish()
        }
    }

    }

视图模型:

    package com.example.quest

import androidx.lifecycle.ViewModel

class SharedViewModel : ViewModel() {
    var question: String ?= null
    var answer: String ?= null

}

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    只需使用by viewModels() 而不传递类名。当你的 ViewModel 有一个空的构造函数时,你不需要传递任何东西。

    使用question.setText(sharedViewModel.question) 代替question.text = sharedViewModel.question。与另一个相同。问题是在 Java 中定义的 TextView 有多个 setText() 方法。 Kotlin 从参数类型与返回值 getText() 匹配的属性中创建一个属性,该属性返回一个 Editable 而不是 String。所以 TextView 的属性访问语法只适用于 Editables 而不是 Strings。

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 1970-01-01
      • 2021-03-01
      • 2019-03-15
      • 2019-04-27
      • 2022-10-04
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多