Skip to content
Advertisement

How to prevent activity to restart after changing its orientation

I’m new to android development using KOTLIN, i have activity that contain fragments like the image below (Image 1), the problem is whenever i try to change the orientation from potrait to landscape, the activity return to the previous activity (Like restart it).

I’ve tried to add android:configChanges="orientation|screenSize|keyboardHidden" to my AndroidManifest.xml, it works perfectly but some says that it’s not recommended to use it.

Could you guys tell me or show me example the best practice to solve this problem ?

IMAGE 1

Image 1

CODE

MainActivity.kt

JavaScript

VisitFragment.kt

JavaScript

LatestVisitFragment.kt

JavaScript

LatestVisitAdapter.kt

JavaScript

Advertisement

Answer

It really is not recommended to prevent activity restart on config changes.

The recommended ways would either by saving and restoring UI state or by using ViewModel. Either one of them can solve your problem but it’s better to use ViewModel approach.


Saving and restoring UI state

Saving state

Right before activity start, but right after config changes have been signaled, override Activity.onSaveInstanceState(Bundle) if you’re saving activity state, or `Fragment.onSaveInstanceState(Bundle) if you’re saving fragment state.

JavaScript

Restoring state

After activity restart due to config changes, restore the previously saved data and apply it to the UI.

JavaScript

Using ViewModel

This approach is relatively new introduced by Google as part of Android Jetpack library. Instead of overriding onSaveInstanceState(Bundle) and checking savedInstanceStatefor null, your data is persisted inside aViewModel` and will survive from configuration changes.

Basic

Initialize your data inside the ViewModel and access them from your activity or fragment.

JavaScript
JavaScript

More about ViewModel

For better usage of ViewModel, it’s better to learn from the official comprehensive guide.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement