While I tested my application on an Android Device turning my Android phone from landscape to portrait, results in all the list items in my list view are disappearing.
Why?
How to manage?
Another most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest. xml. Using this attribute your Activities won't be recreated and all your views and data will still be there after orientation change.
When you rotate your device and the screen changes orientation, Android usually destroys your application's existing Activities and Fragments and recreates them. Android does this so that your application can reload resources based on the new configuration.
You are losing the list items because the default behavior for android during orientation change is to destroy your activity and recreate it. This behavior is chosen to enable android to recreate the activity with a new layout that may be used especially for the new orientation.
To prevent your list items from disappearing there are several thing that have to be done. The first thing that helps during orientation change is to simply reuse the same activity after the change. This can be done through adding this line
android:configChanges="keyboardHidden|orientation"
to the activity tag in your manifest you are experiencing the problem with. This is explained in more detail in this question.
The behavior you explained will likely also appear if the user opens the activity and then sends your application to the background does many other memory heavy stuff to get your application removed from memory and then revisits your app. If this is the case you have to overwrite the onSaveInstanceState method in you activity. How to this is explained in this question.
The simplest way is to use onSaveInstanceState
, explained in Janusz's answer.
However, if there are many items in your list, saving them into a Bundle
in onSaveInstanceState
could slow down the Activity
recreation process, which the users would experience as a lag. To save relatively large data, use onRetainNonConfigurationInstance, then reload data in onCreate
with getLastNonConfugurationInstance
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With