[英]adding items to MutableList using viewmodel
我在保存数据的视图模型文件中创建了一个可变列表
//questions they cheated on
var cheatedList = mutableListOf<Int>(6)
我以这种方式将视图模型文件与具有功能的文件链接起来
private val quizViewModel : QuizViewModel by lazy {
ViewModelProviders.of(this).get(QuizViewModel::class.java)
}
它工作正常,我检查了它。 我需要的只是将整数的内容保存到一个可变列表中......我使用这个 function 这样做
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)
}
好消息是,它将索引保存到列表中......坏消息是一旦我回到另一个活动,列表被破坏并且不再保存任何东西......我如何保持可变列表保存即使我关闭了活动?
如果您希望即使在关闭应用程序并重新打开它(不是临时关闭)后也能保存数据,您可以使用 Room 等本地存储来保存数据......但如果您只想将数据保存在 session 中,则为Tenfour04 说可以使用一个activity和多个fragment并使用一个viewmodel模式来保存.....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.