Junior — Middle
Milliseid meetodeid teate kasutajaliidese oleku salvestamiseks rakendustes?
sobes.tech AI
Vastus AI-lt
To save the state of the user interface in Android applications, the following methods are used:
-
onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle savedInstanceState) — allow saving and restoring the state of an Activity or Fragment during their recreation (e.g., during screen rotation).
-
ViewModel — stores data related to the UI and survives configuration changes without losing the state.
-
SharedPreferences — used for saving simple data (settings, flags) between application sessions.
-
Saving state in databases or files — for more complex or larger data.
-
SavedStateHandle — in conjunction with ViewModel, allows saving and restoring UI state.
Example of saving the state of a text field in an Activity:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("input_text", editText.getText().toString());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String text = savedInstanceState.getString("input_text");
editText.setText(text);
}