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.
时间: 2023-07-02 19:05:30 浏览: 49
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.