【问题标题】:My LiveData variable is not working correctly我的 LiveData 变量无法正常工作
【发布时间】:2022-01-15 23:20:24
【问题描述】:

我有一个 livedata int 值,它的值最初是 3。 在 Fragment Quiz 中,它的值减小,变为 0。但是在 Fragment End 中,它的值仍然是 3,为什么?

视图模型

class QuizViewModel : ViewModel() {
    
    private val lives = MutableLiveData<Int>()
    var live = 3

    init {
        lives.value = live
    }

    fun onWrongAnswer() {
        live--
    }

    fun onPlayAgain() {
        live = 3
    }
}

测验片段

每答错一次,live减1,如果为0或答题完毕,则到达EndFragment。

结束片段

  private fun checkResult() {
        if (viewModel.live == 0) {
            binding.imageViewResult.setImageResource(R.drawable.sad)
            binding.textViewResult.setText(R.string.you_lose_want_to_try_again)
        } else {
            binding.imageViewResult.setImageResource(R.drawable.won)
            binding.textViewResult.setText(R.string.you_win_congratulations)
        }
    }

这部分不能正常工作,因为它仍然是Live 3。但是它的值减少了,变成了0。为什么又是3?

【问题讨论】:

  • 我建议您使用更具表现力的标题以避免被否决。
  • 你对标题有什么建议吗?

标签: android kotlin mvvm viewmodel android-livedata


【解决方案1】:

您检查Int live 而不是MutableLiveData&lt;Int&gt; lives

摆脱live 并创建一个不可变的公共livedata 成员变量。更新视图模型中的可变实时数据:

private val _lives = MutableLiveData<Int>(3)
val lives: LiveData<Int> = _lives
fun onWrongAnswer() {
    _lives.value = lives.value?.minus(1)
}

fun onPlayAgain() {
    _lives.value = 3
}

观察片段中lives: LiveData 的值,如下所示:

viewModel.lives.observe(viewLifecycleOwner, {live ->
    if (live == 0) {
        binding.imageViewResult.setImageResource(R.drawable.sad)
        binding.textViewResult.setText(R.string.you_lose_want_to_try_again)
    } else {
        binding.imageViewResult.setImageResource(R.drawable.won)
        binding.textViewResult.setText(R.string.you_win_congratulations)
    }
})

注意:viewLifecycleOwner 是来自androidx.fragment.app 的属性。

【讨论】:

  • 首先,非常感谢您提供这个描述性的答案。我按照你说的做了,但在这种情况下,我在 QuizFragment 中遇到了一些错误:运算符 '==' cannot be applied to 'LiveData' and 'Int'
  • private fun checkQuestionIndexAndLives() { if (questionIndex == maxIndex || viewModel.lives == 0) { goToEndPage() } else { observeLiveData() } }
  • 您需要访问实时数据中的值。使用viewModel.lives.value == 0
  • 非常感谢,我是这门学科的初学者,您的描述性回答对我有很大帮助。
  • @alicealice 记得将此帖子标记为已回答;)
猜你喜欢
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 2020-11-24
  • 2017-06-10
  • 1970-01-01
  • 2012-12-28
相关资源
最近更新 更多