onRestoreInstanceState没有被调用?

时间:2012-03-30 07:37:10

标签: android

我有一个简单的代码,我想知道在android中程序执行期间何时调用onRestoreInstanceState?

请帮帮我。

提前致谢。

我的第一个活动如下

public class AbcActivity extends Activity {
Button b1;
EditText ed1;
Bundle b = new Bundle();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v("Tag", "inside oncreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    b1 = (Button) findViewById(R.id.button1);
    ed1 = (EditText) findViewById(R.id.editText1);

    b1.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(),
                    SecondActivity.class);
            startActivity(intent);
        }
    });
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    Log.v("Tag", "inside onsave instance state");

    outState.putString("key", ed1.getText().toString());
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    Log.v("Tag", "inside on restore instance state");
    super.onRestoreInstanceState(savedInstanceState);

    if (savedInstanceState != null) {
        Log.v("tag", "inside if");
        String str = savedInstanceState.getString("key");
        ed1.setText("" + str);
    }

}

}

我的第二个活动代码如下

public class SecondActivity extends Activity {
Button back;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.v("Tag", "inside 2 oncreate");
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);

    back = (Button) findViewById(R.id.button1);

    back.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(),
                    AbcActivity.class);
            startActivity(intent);
        }
    });
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    Log.v("Tag", "inside 2 onsave instance state");
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    Log.v("Tag", "inside 2 on restore instance state");
    super.onRestoreInstanceState(savedInstanceState);
}

}

1 个答案:

答案 0 :(得分:2)

正如文件所述:

  

当从先前保存的状态重新初始化活动时,在onStart()之后调用此方法   ...   在onStart()onPostCreate(Bundle)

之间调用此方法

在您被系统杀死后或在配置更改后重新创建Activity时会出现这种情况,并且它在onSaveInstanceState(Bundle)中保存其状态 - 在Activity之前始终调用它1}}被杀了。