单击按钮后,当手机处于纵向位置时,它将文本颜色更改为红色。将配置更改(旋转)到横向位置后,我能够保留包含数字的textview数据,但是颜色改回了textview默认颜色。因此,即使配置更改后,我也希望它保持红色。
private var healthLevel: Int = 10 //Set the initial health level to 10
private lateinit var healthLevelTextView: TextView
private lateinit var sneezeButton: Button
private lateinit var takeMedicationButton: Button
private lateinit var blowNoseButton: Button
private fun changeTextColor() {
// When the health falls to level 7 and below, change the text colour to light blue.
if (healthLevel in 6..7) {
healthLevelTextView.setTextColor(Color.parseColor("#ADD8E6"))
Log.i(TAG, "Called changeTextColor() to light blue when level 7 and below")
}
//The text should be a neutral colour above 7 (Text default color)
else if (healthLevel in 8..10) {
healthLevelTextView.setTextColor(Color.parseColor("#808080"))
Log.i(TAG, "Called changeTextColor() to neutral color when above 7")
}
// If it falls to level 5 and below, change the text colour of the score to red
else if (healthLevel in 5 downTo 0) {
healthLevelTextView.setTextColor(Color.parseColor("#FF0000"))
Log.i(TAG, "Called changeTextColor() to red when level 5 & below")
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("Answer", healthLevel)
Log.i(TAG, "Called SaveInstanceState()")
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
healthLevel = savedInstanceState.getInt("Answer")
val answer = findViewById<TextView>(R.id.health_level)
answer.text = healthLevel.toString()
answer.textColors
Log.i(TAG, "Called restoredInstanceState")
}
最佳答案
在 list 中将此添加到您的 Activity 标签中:
android:configChanges="orientation"
祝你有美好的一天!
关于android - 将手机旋转到横向位置后,如何在onSaveInstanceState()中保存 TextView 颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63750732/