• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Why not to use android:configChanges (on activity) and setRetainInstance(true) (on fragment)

D

Drooxy

Guest
Hi everyone,

I am reading this (good) article :

http://code.hootsuite.com/orientation-changes-on-android/

and because I've been struggling handling configuration change in my code, it seems to me that using android:configChanges (on activity) and setRetainInstance(true) (on fragment) could be a simple way to avoid "problems" (or at least confusion) when a screen orientation change occurs.

In the above article, I read that it is better not to use this solution but I do not read (or I do not understand) good reasons not to to it...

Could someone help me ?

Thank you !
Drooxy
 
Ok so in an app, you can have separate layout XML files for portrait and landscape modes. These layouts could be radically different, as obviously the screen orientation often has an impact on how the UI elements are laid out.

Now I've never used this setRetainInstance(true) method, but from a cursory read of your article, as I understand it, then if you do call this method, the system will retain the same instance of your Activity when the orientation changes, and will not automatically cause the layout to be switched. It's up to your code to switch if required. The default behaviour (not calling the above method), causes the system to destroy your Activities/Fragments on rotation, which loses any state associated with those objects. Therefore when an orientation switch occurs, your Activity must restore the state.

So to answer your question, the reason *not* to call setRetainInstance(true) is because you lose the automatic system behaviour of the layout switching, and you have to write code to switch it yourself. But if orientation switching has no impact on your layout, then it would be more efficient to retain the Activity instance.
 
  • Like
Reactions: scary alien
Upvote 0
Thank you, Scary Alien, for moving my post to the correct area... I'll post there next time !

Thank you, LV426, for your answer. You confirm what I thought : "if orientation switching has no impact on the layout, then it would be more efficient to retain the Activity instance"...

The article was not that clear on that point and I wondered if there was any other reason not to do it... I'll try that - where appropriated - in my current development (I guess it will make code easier to write, to read and to maintain !).

Thanks again to both of you.
Drooxy
 
  • Like
Reactions: scary alien
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones