Junior — Middle
How is the current state of the user interface saved in an application?
sobes.tech AI
Answer from AI
In Android, the mechanism for saving the current interface state (such as input field contents, scroll position, etc.) is used to preserve the state of an activity or fragment.
Main methods:
- Overriding the
onSaveInstanceState(Bundle outState)method, where necessary data is saved intooutState. - Restoring the state from
savedInstanceStatein theonCreate(Bundle savedInstanceState)oronViewCreatedmethod.
This allows the interface to be restored to the same state upon activity recreation (for example, when the screen is rotated).
Example:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("input_text", editText.getText().toString());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String text = savedInstanceState.getString("input_text");
editText.setText(text);
}
}