我一直在研究Android SDK平台,有点不清楚如何保存应用程序的状态。因此,鉴于“你好,Android”示例的这个小工具改造:
package com.android.hello;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
private TextView mTextView = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = new TextView(this);
if (savedInstanceState == null) {
mTextView.setText("Welcome to HelloAndroid!");
} else {
mTextView.setText("Welcome back.");
}
setContentView(mTextView);
}
}
我认为这对于最简单的情况就足够了,但无论我如何离开应用程序,它总是会响应第一条消息。
我确信解决方案就像覆盖 onPause
或类似的东西一样简单,但我已经在文档中戳了 30 分钟左右,没有发现任何明显的东西。
原文由 Bernard 发布,翻译遵循 CC BY-SA 4.0 许可协议
您需要覆盖
onSaveInstanceState(Bundle savedInstanceState)
并将要更改的应用程序状态值写入Bundle
参数,如下所示:Bundle 本质上是一种存储 NVP(“名称-值对”)映射的方式,它将被传递到
onCreate()
以及onRestoreInstanceState()
然后您将在其中提取值从这样的活动:或者来自一个片段。
您通常会使用这种技术来存储应用程序的实例值(选择、未保存的文本等)。