【发布时间】:2021-05-10 16:28:30
【问题描述】:
我在保存数据的视图模型文件中创建了一个可变列表
//questions they cheated on
var cheatedList = mutableListOf<Int>(6)
我将视图模型文件与具有这种功能的文件链接
private val quizViewModel : QuizViewModel by lazy {
ViewModelProviders.of(this).get(QuizViewModel::class.java)
}
它工作正常,我检查了它。我需要的只是将整数的内容保存到可变列表中......我使用这个函数来这样做
showAnswerButton.setOnClickListener {
val answerText = when{
answerIsTrue -> R.string.true_button
else -> R.string.false_button
}
answerTextView.setText(answerText)
//create a function to return the result to MainActivity
setAnswerShownResult(true)
cheaterStatus = true
quizViewModel.cheatedList.add(currentIndex)
println(quizViewModel.cheatedList)
}
好消息是,它将索引保存到列表中......坏消息是一旦我回到另一个活动,列表被破坏并且不再保存任何东西...... 即使我关闭了活动,如何保存可变列表?
【问题讨论】:
-
Take your pick. 或者,如果您不需要记住应用程序会话之间的值,您可以使用 Fragments 而不是 Activities;即使用单个 Activity 来托管所有 Fragment,并将 ViewModel 的范围限定为 Activity 而不是 Fragments。无论如何,这是 Android 团队推荐的(单 Activity 架构)。
-
好像每次销毁activity时都会擦除视图模型中的所有数据...对吧?
-
不,如果 Activity 被临时销毁并重新创建以进行配置更改,则数据将被保留。但是如果 Activity 结束了,那么它的 ViewModel 就被销毁了。
标签: android kotlin viewmodel mutablelist