1. 保存与读取当前状态,MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = "MyLog";
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button2);
if (savedInstanceState != null) {
String s = savedInstanceState.getString("KEY", "");
Log.i(TAG, "onSaveInstanceState:" + s);
textView.setText(s);
}
button.setOnClickListener(view -> textView.setText("This is a message"));
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState:");
outState.putString("KEY", textView.getText().toString());
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy:");
}
}