Sobes.tech
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 into outState.
  • Restoring the state from savedInstanceState in the onCreate(Bundle savedInstanceState) or onViewCreated method.

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);
    }
}
How is the current state of the user interface saved… - sobes.tech