[英]Maintaining state through screen rotation in Kotlin
There's really no code snippet for this.这真的没有代码片段。 I'm building an Android app in Android Studio in Kotlin with a main activity in both default portrait and lanscape modes.
我正在 Kotlin 的 Android Studio 中构建一个 Android 应用程序,在默认纵向和横向模式下都有一个主要活动。 I'm using Android Studio auto-generated
layout\activity_main.xml
and layout-land\activity_main.xml
layouts.我正在使用 Android Studio 自动生成的
layout\activity_main.xml
和layout-land\activity_main.xml
布局。
PROBLEM: When I rotate screens in the app, all widgets reset state.问题:当我在应用程序中旋转屏幕时,所有小部件都会重置 state。 For example, I have a TextView,
tvTitle
, with a default hardcoded string, "Hello World"
.例如,我有一个 TextView,
tvTitle
,带有默认的硬编码字符串"Hello World"
。 tvTitle
normally changed to "News"
while using the app in portrait mode.在纵向模式下使用应用程序时,
tvTitle
通常会更改为"News"
。 I then switched to landscape mode and tvTitle
reverted to it's hardcoded default string, Hello
.然后我切换到横向模式并将
tvTitle
恢复为硬编码的默认字符串Hello
。 How can I retain the state of the app through rotations?如何通过轮换保留应用程序的 state?
Got it.知道了。 The simple answer that works for me here is:
在这里对我有用的简单答案是:
class MainActivity : AppCompatActivity() {
private var SavedVar = "Hello"
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("SavedVar_KEY" ,SavedVar)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(savedInstanceState != null) {
SavedVar = savedInstanceState.getString("SavedVar_KEY")
}
...
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.