Wednesday, 29 February 2012

Android - handling rotation/orientation in an Activity - the easy way!

As I've been asked a few times about the easy way to handle rotation in an Android Activity, I thought I'd outline what you need to do here. It is really easy when you know how!

Firstly, you need to ensure that you create your layouts such that they resize easily. See this post for more details:

Secondly, if you find that you need a different layout for your Activity (say in Landscape mode), create it in a parallel folder to your portait layout like this...:


In your mainfest xml activity... block, make sure you put this:


In your Activity's onCreate() method implementation, pretty much all you need to do is call this method:


Create the following override method in your Activity (this is called when the orientation changes as your Activity is rotated):

public void onConfigurationChanged(Configuration newConfig) {

  // Copy current item values from all your UI gadgets...!
  String myvalue = myitem.toString();
  // etc...

  // Call the method that re-orients and re-creates the gadget bindings

  // Restore the gadget values to the post-rotation UI:

Finally, you can create your new method, which makes your Activity use the correct layout to suit your orientation, and which looks-up all the gadgets, prepares their data and sets-up their event handlers (remember: this is called both at creation time, and whenever a rotation event occurs!):

private void myConfigureUI() {

  // Can check the orientation of the screen...
  if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
  } else {

  // This will automatically pick-up the landscape layout or portrait layout...

  // Look-up new items etc. ... mySpinner is an instance variable in this example...
  mySpinner = (Spinner) findViewById(;

  mySpinner .setOnItemSelectedListener(new OnItemSelectedListener() { ...
  // etc. ...