我是 kotlin 的 android studio 新手。
我想做多項選擇測驗應用程式,我使用資料類和物件常量來提供問題。如果用戶選擇正確的選擇,私有變數 mCurrentPosition(Int) 加 1 和 setQuestion() 作業來改變問題、選擇和正確選擇。
為了防止app關閉后進度被重置,我認為如果mCurrentPosition的int被存盤就可以了,所以我使用了onSaveIntanceState。但是在關閉應用程式后會初始化進度......
class QuizActivity : AppCompatActivity() {
private var mCurrentPosition: Int = 1
private var mQuestion300List: ArrayList<Question300>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(savedInstanceState != null) {
with(savedInstanceState) {
mCurrentPosition = getInt(STATE_SCORE)
}
} else {
mCurrentPosition = 1
}
setContentView(R.layout.activity_quiz)
val questionList = Constant.getQuestions()
Log.i("Question Size", "${questionList.size}")
mQuestion300List = Constant.getQuestions()
setQuestion()
tv_choice1.setOnClickListener {
if (tv_correctChoice.text.toString() == "1") {
mCurrentPosition
setQuestion()
} else {
tv_choice1.setBackgroundResource(R.drawable.shape_wrongchoice)
}
}
tv_choice2.setOnClickListener {
if (tv_correctChoice.text.toString() == "2") {
mCurrentPosition
setQuestion()
} else {
tv_choice2.setBackgroundResource(R.drawable.shape_wrongchoice)
}
}
tv_choice3.setOnClickListener {
if (tv_correctChoice.text.toString() == "3") {
mCurrentPosition
setQuestion()
} else {
tv_choice3.setBackgroundResource(R.drawable.shape_wrongchoice)
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState?.run {
putInt(STATE_SCORE, mCurrentPosition)
}
super.onSaveInstanceState(outState)
}
companion object {
val STATE_SCORE = "score"
}
private fun setQuestion() {
val question300 = mQuestion300List!![mCurrentPosition-1]
tv_question.text = question300!!.question
tv_choice1.text = question300.choice1
tv_choice2.text = question300.choice2
tv_choice3.text = question300.choice3
tv_correctChoice.text = question300.correctChoice
tv_now.setText("${mCurrentPosition}")
tv_choice1.setBackgroundResource(R.drawable.shape_problem)
tv_choice2.setBackgroundResource(R.drawable.shape_problem)
tv_choice3.setBackgroundResource(R.drawable.shape_problem)
}
}
這是我的應用程式代碼。請幫幫我 :) 謝謝
uj5u.com熱心網友回復:
savedInstanceState 真的只適用于兩件事
- 幸存的旋轉,在那里
Activity被摧毀和重建 - 系統在后臺殺死您的應用程式 - 因此,當您回傳時,
Activity需要按原樣重新創建應用程式,因此用戶看不到僅在后臺運行的應用程式與被殺死以節省資源的應用程式之間的任何區別
當onCreate運行時,如果Activity正在從以前的狀態重新創建,你會得到作為通過捆綁savedInstanceState-這包含所有你添加的東西onSaveInstanceState應用較早停止前。但是,如果用戶關閉應用程式(或者通過與后退按鈕打了退堂鼓,或刷應用遠去的任務切換等),那么算作一個的新的開始與無狀態恢復。并且savedInstanceState將為空onCreate(這是您可以檢查它是否是一個新的開始的一種方式)。
因此,如果您想在用戶明確關閉應用程式后仍保持狀態,則需要使用其他內容。這是有關該主題的檔案- 典型的方法是SharedPreferences用于小資料,某種資料庫,如用于較大狀態的 Room。DataStore如果你想嘗試一下,這是新事物
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/385528.html
標籤:安卓工作室 科特林 android-生命周期
