Sobes.tech
Junior — Middle

What methods exist for preserving the user interface when changing the orientation or configuration of the device?

sobes.tech AI

Answer from AI

When the orientation or configuration of an Android device changes, the activity by default is recreated, which leads to the loss of UI state. The following methods are used to preserve the UI:

  1. onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle savedInstanceState) — allow saving and restoring UI state, such as input field contents.

  2. ViewModel — stores data related to the UI and survives configuration changes, preventing loss of state.

  3. Retain Fragment — a fragment with setRetainInstance(true) that is preserved during activity recreation.

  4. Using layout resources for different configurations — for example, different layout files for portrait and landscape orientations.

  5. Handling configuration changes manually via android:configChanges in the manifest to prevent activity recreation (not recommended for complex UIs).

Example of saving input field state:

@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);
}