回答

收藏

如何使用保存实例状态保存活动状态?

技术问答 技术问答 575 人阅读 | 0 人回复 | 2023-09-11

我一直在研究Android SDK平台,有点不清楚如何保存应用程序的状态。所以,鉴于你好,Android这个小工具的改造示例:' h6 y) X( ]% u# Q

    : _- u; y/ P& k
  • 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); }code]我认为这对最简单的情况就足够了,但无论我如何离开应用程序,它总是会回应第一条信息。& g' M2 m5 I: R
  • 我相信解决方案就像覆盖一样onPause或者类似的东西一样简单,但我在文档中戳了大约30分钟,没有发现任何明显的东西。0 I% I1 h- n  f8 v0 H" s
  •                                                                
    - n' S& H, d1 V
  •     解决方案:                                                               ' |. z7 R/ \: W/ V/ u, T: v
  •                                                                 您需要覆盖onSaveInstanceState(Bundle savedInstanceState)并将要改变的应用程序状态值写入Bundle参数如下:[code]@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.}
    $ p7 n% N; U& m! k3 `
Bundle  本质上是一种存储 NVP(“名称-值对)映射的方式将传输到onCreate()您onRestoreInstanceState()从活动中提取值的位置如下:  Q+ J& M& ?5 C; s
    @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");}2 N9 C) C' @$ U3 u
或者来自一个片段。2 E' H2 K' G$ u! O$ ?  O( }
    @Overridepublic void onViewStateRestored(@Nullable Bundle savedInstanceState)    super.onViewStateRestored(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");}+ o  ^% q2 m4 W' H& p
您通常使用该技术来存储应用程序的实例值(选择、未保存的文本等)。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则