我有一个超简单的计算器,可以将一些数字输出到 4 个单独的标签。对于用户体验来说,标签保存应用程序终止、后退按钮等数据是至关重要的。
目前我按照说明设置了 userPreferences 。看起来超级简单,但是在不同情况下返回活动屏幕时,所有标签都包含与仅其中一个标签相同的数字。例子:
实际的:
label 1: 90
label 2: 90
label 3: 90
label 4: 90
预期的:
label 1: 90
label 2: 2030
label 3: 40654
label 4: *list of calculations from above numbers*
我已经尝试了从覆盖乐趣 onResume、onStart、onRestart 以及保存在 onStop、onPause、onDestroy 等中检索数据的各种组合......没有任何效果,仍然与上述相同的输出。
编辑:积极的一面是,用户偏好确实在所有生命周期情况下保存了一个标签数据......
这是我现在的代码,没有任何活动生命周期尝试:
class Calc : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.KITKAT)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT //Set Portrait only
setContentView(R.layout.activity_calc)
// Instantiate SharedPreferences for saving user input
val pref: SharedPreferences = applicationContext.getSharedPreferences("MyPref",
MODE_PRIVATE) ?: return // Call to assign saved value
val editor: SharedPreferences.Editor = pref.edit() // Call editor. to save to file
// Retrieve saved data if it exists
if (pref.contains(UNIT) &&
pref.contains(VOLUME) &&
pref.contains(HEIGHT) &&
pref.contains(CALCULATION)) {
unit.text = pref.getString(UNIT, "")
volume.text = pref.getString(VOLUME, "")
height.text = pref.getString(HEIGHT, "")
calculation.text = pref.getString(CALCULATION, "")
}
val popup = Utilities
// Declare calculate button and call function to crunch numbers and output them
calculateButton.setOnClickListener {
hideKeyboard() // Hide keyboard on button press
editor.clear() // Clears saved data
//
// Bunch of calculator code that assigns numbers to 4 output labels...
//
// Save data to sharedPreferences
editor.putString(UNIT, outputUnit.text.toString())
editor.putString(VOLUME, outputVolume.text.toString())
editor.putString(HEIGHT, outputHeight.text.toString())
editor.putString(CALCULATION, outputCalculation.text.toString())
editor.apply() // Finalizes save asynchronously
}
}
}
在 .Kt 文件中实例化:
const val UNIT = ""
const val VOLUME = ""
const val HEIGHT = ""
const val CALCULATION = ""