在当前的ViewModel中使用ViewModelProvider的正确方法是什么?

时间:2019-12-29 22:55:49

标签: android kotlin

我的错误似乎是在“ QuotesActivity”类中初始化ViewModelProvider时。该应用程序编译正常,但单击提交按钮时,屏幕上报价的更新不起作用。我在其他课程中慢慢浏览了所有代码,一切看起来都很好。我发现ViewModelProvider是我搞砸的地方。

package com.example.mvvmprep.ui.quotes

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.mvvmprep.R
import com.example.mvvmprep.Utilities.InjectorUtils
import com.example.mvvmprep.data.Quote
import kotlinx.android.synthetic.main.activity_quotes.*

class QuotesActivity : AppCompatActivity() {

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

private fun initializeUi() {
    val factory = InjectorUtils.provideQuotesViewModelFactory()
    val viewModel = ViewModelProvider(this, factory).get(QuotesViewModel::class.java)


    // Observing LiveData from the QuotesViewModel which in turn observes
    // LiveData from the repository, which observes LiveData from the DAO ☺
    viewModel.getQuotes().observe(this, Observer { quotes ->
        val stringBuilder = StringBuilder()
        quotes.forEach { quote ->
            stringBuilder.append("$quote\n\n")
        }
        textView_quotes.text = stringBuilder.toString()
    })

    // When button is clicked, instantiate a Quote and add it to DB through the ViewModel
    button_add_quote.setOnClickListener {
        val quote = Quote(editText_quote.text.toString(), editText_author.text.toString())
        viewModel.addQuote(quote)
        editText_quote.setText("")
        editText_author.setText("")
    }
}
}

0 个答案:

没有答案