首页 > 解决方案 > 将手机旋转到横向位置后,如何在 onSaveInstanceState() 中保存文本视图颜色?

问题描述

单击按钮后,当我的手机处于纵向位置时,它会将文本颜色更改为红色。在将配置更改(旋转)到横向位置后,我能够保留包含数字但颜色更改回 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")
    }

标签: androidkotlinkotlin-android-extensions

解决方案


在清单中将此添加到您的活动标签中:

android:configChanges="orientation"

祝你有美好的一天!


推荐阅读