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:
-
onSaveInstanceState(Bundle outState) and onRestoreInstanceState(Bundle savedInstanceState) — allow saving and restoring UI state, such as input field contents.
-
ViewModel — stores data related to the UI and survives configuration changes, preventing loss of state.
-
Retain Fragment — a fragment with
setRetainInstance(true)that is preserved during activity recreation. -
Using layout resources for different configurations — for example, different layout files for portrait and landscape orientations.
-
Handling configuration changes manually via
android:configChangesin 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);
}