Wednesday, March 23, 2011

Android: "Smart Folders"

I love clean code. One of the features android has that makes it easier to write clean code is a feature I nicknamed "Smart Folders". Take for example this scenario: You would like your application to have different layouts based on the screen orientation. Your first try might look something like this

public void onCreate(Bunde icicle)
{
       super.onCreate(icicle);
       int orientation = getResources().getConfiguration().orientation;
       if (orientation = Configuration.ORIENTATION_PORTRAIT)
       {
              setContentView(R.layout.main_port);
        } else if(orientation = Configuration.ORIENTATION_LANDSCAPE)
       {
             setContentView(R.layout.main_land);
       }
}

Then you stumble across this post and magically your code turns into this:

public void onCreate(Bunde icicle)
{
       super.onCreate(icicle);
       setContentView(R.layout.main);
}

You ask how is this possible? Simple: Android at runtime checks the configuration of the phone and looks in your /res folder for matching Resource Directory Qualifiers and uses the correct resources accordingly. WHAT THE HECK DOES THAT MEAN?   I hear you sayin'?

It means that if Android detects that the phone is in landscape mode it will check the /layout-land directory/folder for the main.xml . If it can't find a match then it defaults to checking the regular layout folder. Not only does this make your code easier to read but it will also make it more manageable down the road.

For a list of all the qualifiers android offers look Here (Scroll down a little to see the table) 
Some of the qualifiers include

  • Language and region: So you can Localize your strings
  • Screen size and/or Screen pixel density (dpi) : So your app looks good on any screen
  • Keyboard availability: So you can control when to show the soft keyboard
  • Primary non-touch navigation method: So you can support trackballs and trackpads!


TL;DR:
1. Put main_port.xml in the /layout  directory/folder
2. Put main_land.xml in the /layout-land directory/folder
3.Rename both xml's to main.xml

Piece of Cake! Next Post will be a tutorial on how to set up your app project with a new Google Code Project and how to easily sync your code to your project with the Mercurial Eclipse Plug-in. Please Stay tuned and pass this around.

PS: Write any suggestion in my comments or contact me on twitter: @tytdfn

No comments:

Post a Comment

Hey There! Please leave a comment, suggestion, or the occasional flame (but only if its informational!)