屏幕旋转时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
相关产品推荐
相关产品推荐

