This is one possible solution to the first challenge in chapter 6. Hopefully this helps someone struggling with this challenge. My solution was to create a ViewModel for CheatActivity called CheatViewModel
Note: this is only for persisting UI state for a configuration change, not a process death scenario.
CheatActivity.kt:
package com.bignerdranch.android.geoquiz
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModelProviders
private const val EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true"
const val EXTRA_ANSWER_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown"
class CheatActivity : AppCompatActivity() {
private var answerIsTrue = false
private lateinit var answerTextView: TextView
private lateinit var showAnswerButton: Button
private val cheatViewModel: CheatViewModel by lazy {
ViewModelProviders.of(this).get(CheatViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cheat)
answerIsTrue = intent.getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false)
answerTextView = findViewById(R.id.answer_text_view)
showAnswerButton = findViewById(R.id.show_answer_button)
showAnswerButton.setOnClickListener {
val answerText = when {
answerIsTrue -> R.string.true_button
else -> R.string.false_button
}
answerTextView.setText(answerText)
setAnswerShownResult()
cheatViewModel.answerWasClicked = true
}
if (cheatViewModel.answerWasClicked) {
answerTextView.setText(R.string.true_button)
setAnswerShownResult()
}
}
private fun setAnswerShownResult() {
val data = Intent().apply {
putExtra(EXTRA_ANSWER_SHOWN, true)
}
setResult(Activity.RESULT_OK, data)
}
companion object {
fun newIntent(packageContext: Context, answerIsTrue: Boolean): Intent {
return Intent(packageContext, CheatActivity::class.java).apply {
putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue)
}
}
}
}
CheatViewModel.kt:
package com.bignerdranch.android.geoquiz
import androidx.lifecycle.ViewModel
class CheatViewModel: ViewModel() {
var answerWasClicked = false
}