You are viewing...

Handling Android's rotation/orientation changes.

Updated on June 24, 2012 at the 20th hour
Posted under:

DISCLAIMER: All views are considered my own and you should not draw any conclusions on associates.

One thing I've encountered with Android since my internship was handling the orientation changes. Orientation changes are part of a wider thing called configuration changes which will kill your activity and start it over (personally I think is stupid, but it make sense). Killing your activity and making it restart will possibly change the layout according to your layout structure (layout-port, layout-land, etc etc etc). Read about it here.

So at first, I assumed adding orientation|keyboardhidden to the activity in androidmanifest.xml was sufficient because it would send the configuration changes to the activity and let me handle it. Which was great for me and a easy fix. Not until I started to want to use different layouts such as layout-port and layout-land for dialogs in particular (keep in mind I'm using the showdialog function) since what fits in a tablet doesn't mean it fits on a phone. Since I was the one who had to handle the configuration changes that meant I had to switch out the content views, but dialogs don't have a way to handle configuration changes.... This is where the Fragments API comes in.

Fragments, which are basically sub-activities, allow you to handle config changes which is a good thing because now I have the power to change whatever I'd want to change under the configuration change. What I have/had at the time is that user interface is handled by one particular activity with a WebView and possibly a dialog over it. I needed the dialog to change to a different layout according to the structure, but the WebView just had to adjust, so I got rid of all my calls to showdialog() and changed every view/dialog into a Fragment/DialogFragment. With this conversion, I could add a setContentView to the resource id or whatever I wanted to do in the onConfigurationChanged call to the fragment, which would reset the layout. Any listeners or etc. you had attached to the previous layout have to be re-attached to the new layout, so a setupView function is useful.

It takes a while to understand how fragments work exactly when you come from using only Activities (a la < 3.0 Honeycomb). I don't completely understand how they work, but I have an idea, so I am moderately alright with it. When I looked at fragments at first, I thought it was a stupid idea to use it even with the support library, but now i see the practicality of it.

As usual with any Android post, people if you are reading this GET an Android 4.0 phone and dump your previous phone!
You just read "Handling Android's rotation/orientation changes.". Please share if you liked it!
You can read more recent posts here.