问题描述
//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)
}
好消息是,它将索引保存到列表中...坏消息是一旦我移回另一个活动,列表就会被销毁,并且不再保存任何内容... 即使我关闭了活动,我如何保持可变列表的保存?
解决方法
如果您希望在关闭应用程序并重新打开后仍保存数据(不是临时关闭),您可以使用 Room 等本地存储来保存数据... 但是,如果您只想将数据保存在会话中,那么正如 Tenfour04 所说,您可以使用一个活动和多个片段并使用单个视图模型模式来保存.....