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:
http://sseyod.blogspot.com/2010/09/art-of-scalable-android-layouts.html

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...:

res/layout/fred.xml
res/layout-land/fred.xml


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

android:configChanges="orientation|keyboardHidden"


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

  myConfigureUI();


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

@Override
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
  myConfigureUI();

  // Restore the gadget values to the post-rotation UI:
  myitem.setText(myvalue);
}


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) {
    setContentView(R.layout.main_landscape);
  } else {
    setContentView(R.layout.main);
  }
  */

  // This will automatically pick-up the landscape layout or portrait layout...
  setContentView(R.layout.main);

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

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