onRestoreInstanceState
时间: 2024-01-07 21:05:06 浏览: 52
onRestoreInstanceState() 是一个 Android 生命周期方法,用于恢复之前保存的 Activity 状态。当 Activity 被系统销毁并重新创建时,系统会调用此方法以恢复 Activity 的先前状态。该方法接收一个 Bundle 参数,其中包含之前保存的数据。开发人员可以从 Bundle 中提取数据并将其用于恢复 Activity 的状态,以便用户可以在恢复后继续操作。
相关问题
onrestoreinstancestate
onRestoreInstanceState是Android中的一个方法,用于在Activity被销毁后重新恢复其状态。当Activity被销毁并重新创建时,系统会调用onRestoreInstanceState方法来恢复之前保存的状态。在这个方法中,我们可以通过Bundle参数获取之前保存的状态数据,并将其恢复到Activity中。这个方法通常用于处理屏幕旋转等配置变化时的状态保存和恢复。
The MainActivity class of an app includes an Integer variable that is initialized to a default value. This variable is then modified in the method onClickButton() associated with a button. The user notices that after a button click and a screen reorientation e.g. from portrait mode to landscape mode, the variable has still the default value. Describe how to solve this problem and make the variable value persistent after reorientation. You may include the methods and objects to use in your answer.
To make the variable value persistent after a screen reorientation, we need to save the state of the MainActivity instance. We can achieve this by using the onSaveInstanceState() method and the onRestoreInstanceState() method.
In the onSaveInstanceState() method, we can save the value of the integer variable into the Bundle object. This Bundle object will be passed to the onRestoreInstanceState() method when the activity is recreated. In the onRestoreInstanceState() method, we can retrieve the saved value from the Bundle object and set it back to the integer variable.
Here is an example code snippet:
```
public class MainActivity extends AppCompatActivity {
private static final String VAR_KEY = "var_key";
private int myVar = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
myVar = savedInstanceState.getInt(VAR_KEY, 0);
}
Button myButton = findViewById(R.id.my_button);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myVar++;
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(VAR_KEY, myVar);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myVar = savedInstanceState.getInt(VAR_KEY, 0);
}
}
```
In this example, we define a static final key for the variable in the Bundle object. In the onCreate() method, we check if there is a saved instance state and retrieve the saved value if there is one. We also set the onClickListener for the button to modify the value of the integer variable.
In the onSaveInstanceState() method, we save the value of the integer variable into the Bundle object using the key we defined earlier. In the onRestoreInstanceState() method, we retrieve the saved value from the Bundle object and set it back to the integer variable.