android - 将手机旋转到横向位置后,如何在onSaveInstanceState()中保存 TextView 颜色?

标签 android kotlin kotlin-android-extensions

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

相关文章:

android - 一个 Google Play 开发者帐户有多个 Google Merchant 帐户?

android - Kotlin 中的通用类类型用法

安卓自定义 View : Delegate attributes to controls inside of view

android - 无法找到明确的 Activity (Kotlin)

java - 如何在 Java 中为 Android 设置 HttpResponse 超时

android - 画廊工作中的文件选择器,但它不适用于 android webview 中的相机

android - 将 TensorFlow python 代码与 android 应用程序一起使用

kotlin - 使用 Gradle 和 Kotlin 构建自执行 JAR

Kotlin - 嵌套函数与具有 1 个调用点的私有(private)函数

android - 如何在 Android 上使用定时器进入 recyclerView