如何使用保存实例状态保存Android Activity状态?

如何使用保存实例状态保存Android Activity状态?,第1张

概述我一直在研究AndroidSDK平台,有点不清楚如何保存应用程序的状态.因此,考虑到’Hello,Android’示例的这种小型重新设计:packagecom.android.hello;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclassHelloAndroidexten

我一直在研究Android SDK平台,有点不清楚如何保存应用程序的状态.因此,考虑到’Hello,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分钟左右并且没有找到任何明显的东西.

解决方法:

您需要覆盖onSaveInstanceState(Bundle savedInstanceState)并将要更改的应用程序状态值写入Bundle参数,如下所示:

@OverrIDepublic voID onSaveInstanceState(Bundle savedInstanceState) {  super.onSaveInstanceState(savedInstanceState);  // Save UI state changes to the savedInstanceState.  // This bundle will be passed to onCreate if the process is  // killed and restarted.  savedInstanceState.putBoolean("MyBoolean", true);  savedInstanceState.putDouble("myDouble", 1.9);  savedInstanceState.putInt("MyInt", 1);  savedInstanceState.putString("MyString", "Welcome back to AndroID");  // etc.}

Bundle本质上是一种存储NVP(“名称 – 值对”)映射的方式,它将被传递到onCreate()和onRestoreInstanceState(),然后您将提取这样的值:

@OverrIDepublic voID onRestoreInstanceState(Bundle savedInstanceState) {  super.onRestoreInstanceState(savedInstanceState);  // Restore UI state from the savedInstanceState.  // This bundle has also been passed to onCreate.  boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");  double myDouble = savedInstanceState.getDouble("myDouble");  int myInt = savedInstanceState.getInt("MyInt");  String myString = savedInstanceState.getString("MyString");}

您通常会使用此技术来存储应用程序的实例值(选择,未保存的文本等).

总结

以上是内存溢出为你收集整理的如何使用保存实例状态保存Android Activity状态?全部内容,希望文章能够帮你解决如何使用保存实例状态保存Android Activity状态?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1104576.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存