You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

屏幕旋转时Activity无法保存对数正态随机值的问题

问题原因及修复方案

核心问题

你错误重写了带PersistableBundle参数的onSaveInstanceState和onRestoreInstanceState方法。这两个方法仅在Activity的Manifest配置了android:persistableMode="persistAcrossReboots"时才会被系统调用,而普通屏幕旋转场景下,系统会调用仅含Bundle参数的版本。因此你的状态保存逻辑根本没有执行,旋转后恢复的是randomValue的初始值0.0。

修复步骤

1. 修正onSaveInstanceState方法

替换为系统默认调用的无PersistableBundle参数版本:

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putDouble("randomValue", randomValue)
}

2. 选择一种状态恢复方式

方式一:修正onRestoreInstanceState方法

同样使用无PersistableBundle参数的版本:

override fun onRestoreInstanceState(savedInstanceState: Bundle) {
    super.onRestoreInstanceState(savedInstanceState)
    randomValue = savedInstanceState.getDouble("randomValue")
    findViewById<TextView>(R.id.random_number_result).text = randomValue.toString()
}

方式二:在onCreate中恢复状态

确保在获取TextView实例后执行恢复逻辑:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val mean = findViewById<EditText>(R.id.mean_val)
    val vari = findViewById<EditText>(R.id.variance_value)
    val bttn = findViewById<Button>(R.id.get_random_num)
    val textv = findViewById<TextView>(R.id.random_number_result)

    // 恢复保存的随机值
    savedInstanceState?.let {
        randomValue = it.getDouble("randomValue")
        textv.text = randomValue.toString()
    }

    bttn.setOnClickListener {
        val mean_val = mean.text.toString().toDouble()
        val std_dev = vari.text.toString().toDouble()

        randomValue = generatedLogNormalRandom(mean_val, std_dev)
        textv.text = randomValue.toString()
    }
}

额外注意

  • 如果你坚持使用带PersistableBundle的方法,需要在AndroidManifest.xml中对应Activity标签添加android:persistableMode="persistAcrossReboots",但这只适用于跨设备重启的持久化场景,普通屏幕旋转没必要这么做。
  • 调用getDouble时可以指定默认值,比如it.getDouble("randomValue", 0.0),避免键不存在时出现异常(不过正常保存后不会有这个问题)。

内容的提问来源于stack exchange,提问作者Uladzislau Kaplan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:45:07