1. Are you ready for the Galaxy S20? Here is everything we know so far!

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

Discussion in 'Android Development' started by Drooxy, Mar 16, 2016.

  1. Drooxy

    Drooxy Guest
    Thread Starter

    Hi everyone,

    I am reading this (good) article :


    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 !

  2. scary alien

    scary alien not really so scary

    Welcome to AF :).

    I've moved your thread over here to our Application Development area for you.

  3. Deleted User

    Deleted User Guest
    Thread Starter

    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.
    scary alien likes this.
  4. Drooxy

    Drooxy Lurker

    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.
    scary alien likes this.

Share This Page