How to refresh an Android RelativeLayout when orientation changes without restarting the Activity?

后端 未结 2 1343
误落风尘
误落风尘 2021-01-28 04:07

I have an Android Activity with a RelativeLayout and I have implemented the following method to prevent the activity from being recreated on change of Orientation:



        
相关标签:
2条回答
  • 2021-01-28 05:00

    You have two ways:

    • Retaining an Object During a Configuration Change
    • Handling the Configuration Change Yourself

    You have chosen the second way. In this case you have to reassign every resource by hand and this approach is not recommended.

    IMHO the best way is the first by implementing the method: onRetainNonConfigurationInstance();

    Here a complete example on howto use.

    Note: the onCreate will be called again but you can adjust your code to prevent long runnning task to be called again during a configuration change

    0 讨论(0)
  • 2021-01-28 05:00

    There is a third and easier way that is missing in Francescos answer.

    Just add

    android:configChanges="keyboardHidden|orientation"
    

    to the activity tag of every activity that you don't want to restart on a change from landscape to portrait mode. This will cause the OS to rebuild your layout without destroying it before the rebuild. The oncreate method will not get called again and you don't loose the state of the activity. But be carefull this will only work if you use the same layout file for portrait and landscape mode.

    See this question for more information on this topic

    0 讨论(0)
提交回复
热议问题