X Forward

Android for iPhone Developers - Part 2

Apr 4, 2009

Dive into the world of Android user interface creation.

This is Part 2 in the Android for iPhone Developer series.

No Interface Builder, No Problem
Android does not provide a graphical user interface design application like Interface Builder. But don’t worry, you won’t be writing your UIs programatically. Android uses XML-based layout files to define interfaces.

It may not be as slick as using Interface Builder, but layout files are very powerful and pretty easy to use. Think of them as NIB files that you edit manually.

Let’s look at a simple layout file right now. In your project expand the “res” folder, then the “layout” folder and double-click the main.xml file.

Before we get into the layout file, I want you to note the directory hierarchy we just traversed. This hierarchy must be maintained. That means don’t pull the layouts directory out of the res directory, or don’t put layout files in the drawable directory. Trust me on this one, just leave the directories like they are.

OK, on to the layout (you may have to click on the “main.xml” tab at the bottom of the pane to view the actual XML).  The first thing you’ll note is the tag named “LinearLayout”. Your layouts will always start with a tag similar to this one. It defines the type of layout manager the system will use internally to organize any UI elements you put into it. I’m going to leave it up to you to read about all the different kinds of layouts available, but I will briefly explain the LinearLayout.

Since you don’t have drag-and-drop functionality to define exactly where each UI element should be placed, the layouts use pre-defined algorithms to do figure out where elements should be drawn. Our LinearLayout here uses a simple concept to decide where to draw your elements. It draws them in the order they are defined in the layout XML from top to bottom (or if you’ve defined the layout as horizontal, from left to right). That’s it. The LinearLayout just starts stacking your UI elements on top of each other. Now let’s look at a simple UI element, the TextView.

You should see a TextView tag as a child of the LinearLayout. Think of a TextView as a UILabel, its just an easy way to draw text to the screen. Notice the 2 attributes: android:layout_width and android:layout_height. These are common to all UI elements and they define how the width and height of the element should be drawn. The 2 values being used are fill_parent and wrap_content, these are the 2 most common values for layout_width and layout_height.

The fill_parent value is pretty self-explanatory. It tells the layout to draw the element the same width as the parent, which in this case happens to be the layout itself which is taking up the entire screen (as defined in the layout tag layout_width and layout_height attributes). The wrap_content value is also simple to understand. It simply makes the width or height the correct value to only just encase the content. So, if your text is only 15 pixels tall the height will be set to match this.

That’s the basics of laying out a UI. I know this example is trivial, but there is knowledge to be gained from it. It’s easier to see concepts and understand them when there’s not a lot of noise around them.

You may be saying to yourself, “Well that’s all fine and good, I can put a text view in a layout and display it, but how do I get a pointer to it so I can manipulate it in code?”. Patience, grasshopper, that is in the next section.


Getting Pointers to UI Elements in Code
You’re used to using the IBOutlet descriptor when defining instance variables in your UIViewController so you can hook them up to their corresponding UI elements in Interface Builder. Well, we don’t have that mechanism in Android, but getting pointers to UI elements is really simple, and its done in code.

But before we can start getting handles to UI elements, they need to be instantiated. Since they live in a layout, we need to get the layout instantiated, then all of its elements will come alive. You know how you can load UIViewControllers programatically with NIB files using the initWithNibName method? Good, because there’s basically a straight analog for it in Android. Let’s see it in action, expand the “src” directory in the project pane, then expand the package (in my case it’s called com.xforward.samples, but yours will be named whatever you put in the initial dialog to create the project. Now double-click the activity java file, mine is called MainActivity.java, but yours will be named whatever you put in as the activity name in the initial dialog that we used to create the project.

Not much in there, right? That’s fine, we only want to see the line with the call to setContentView(R.layout.main), because that’s our initWithNibName analog. The setContentView() method is inherited from the Activity super class and does exactly what its name implies. It takes a layout resource ID as a parameter, as you can see the layout ID is stored in a class called “R”. I’m not going to get into the details of how this class is created or any of that stuff, just know that it is automatically generated off of the resource files in your project’s res directory. Think of the R class as your application’s bundle, it’s how you get programatic access to your applications resources.

This would be a good time to point out that we are looking at a method called onCreate(). This method is one of many that are called as various events occur that concern your activity. You simply override the ones your interested in. This particular method is one you’ll always want to override because without it, your activity will have no view to control. The onCreate() method is similar to a UIViewController’s initWithNibName method, except you are not passed the name of the resource file to load (your are actually passed a Bundle object that represents the state of your application, but that’s beyond the scope of this article). That may be a bit confusing so think of it like this: when you create a new activity, override the onCreate() method so you can define the activity’s view.

Let me stop for a minute. You may have noticed that I draw 2 parallels to the initWithNibName method; setContentView() and onCreate(). Allow me to clear up any ambiguities caused by this: setContentView() is called by the activity to load the view for *itself*, onCreate() is called by the system to let the activity know that it has been created and should do something, sort of like viewDidLoad but no view has been loaded yet. If you’re still scratching your head, think of it like this: onCreate() and setContentView() work together to complete the tasks of initWithNibName and viewDidLoad. onCreate() informs your activity that it should load it’s view and perform any additional initialization, and setContentView() simply loads the view from a resource and associates it with your activity’s view.

Now that we’ve got our view all loaded up, let’s get a handle on a UI element object. If you look at the resource file in res/layout/main.xml, you’ll see that it has one element inside the layout tag. This tag defines a TextView object (remember this is basically a UILabel), and if we want access to it in our code (say, to change the text it is displaying based on the state of the application) we need a handle for it. Let’s do that now.

The first thing we need to do is give our TextView element an ID so we’ll have a way to ask for it when we want it. Go to the res/layout/main.xml file and add the following attribute to the TextView tag:

android:id=”@+id/myTextView”

Don’t worry about the weird syntax, just know that’s how you have to do it. This attribute assigns an ID to this element, now we’ll be able to access it via the R class.

Back in our activity class, define a new instance variable of type TextView and call it myTextView. Now, go to your activity’s onCreate() method and add the following line *after* the call to setContentView().

myTextView = (TextView)findViewById(R.id.myTextView);

Bam! Now you’ve got a reference to the TextView in the layout. Just for fun, let’s change the text of our TextView. Add the following line:

myTextView.setText(“This is *my* TextView!”);

FYI: The best place to find out about available UI elements is in the android.widgets package (http://developer.android.com/reference/android/widget/package-summary.html).
Now all we need to do is compile and run our little sample application and admire our handiwork.

Coming soon: Part 3 - Compilation, Simulation, and on Device testing

Comments

Business mailing lists

05/30/09 07:02 am

Crown Lists is a mailing list broker offering high quality business mailing lists, consumer mailing lists, direct marketing lists, medical mailing lists, email lists. We are a mailing
list company helping clients purchase lists.
http://www.CrownLists.com

Birth Injury Resource

06/08/09 11:02 am

Law firm helps families with children
with a birth injury caused by medical
malpractice.

Skinny coffee

06/08/09 12:32 pm

I just wonder when can we use this technology…

website design

06/11/09 08:26 am

This would be the best thing technology has ever made.

casino forum

06/11/09 11:37 pm

Was this a nice way for t mobile get existing customers to upgrade to the G2 at a for another $399 since existing customers don’t qualify for the full discount on upgrades until after 22 months on a two year agreement?? what about those who got the g1 and had to extend another two years and didn’t realize until after 14 days how inferior and crappy the g1 is even compared to a sidekick??
Was this supposed to be an Iphone killer?? The thought of that is beyond laughable. The G1 can’t even hold a battery charge longer than 3 hours, are we supposed to trust that the G2 along with T mobiles ‘wonderful’ customer service will be better?

Carports

06/22/09 09:51 am

Nice post! The article really is interesting… Hope to here more about the updates of this technology.

Work from home

06/24/09 01:20 pm

Technology is really evolving. And I can say that it’s quite fast.

Fetal Distress

07/01/09 07:59 am

This is one of the best technology ever made and it’s good thing technology is evolving fast.

There is no doubt that technology has really been evolving more in the past few years. This is really amazing!

Mailing list broker

07/03/09 06:35 am

Find Lists is a mailing list broker offering high quality business mailing lists, consumer mailing lists, direct marketing lists, medical mailing lists, email lists. We are a mailing list company helping clients purchase lists. http://www.findlists.com

Stillbirth resource

07/03/09 03:15 pm

Thanks for sharing this article. Really good improvements.

Hungarian Civil Engineering

07/06/09 09:53 am

This topic is really interesting. The technical information is really impressive.

blog

07/07/09 09:27 am

Nice. Thanks..

sohbet odaları

07/07/09 11:51 am

thanks you

Custom Electronic Design

07/08/09 09:46 am

People are really enjoying the convenience of technology.

Dog Training Sarasota

07/08/09 09:50 am

Technology has been like the backbone of almost every business!

teknogroup

07/08/09 02:16 pm

Thanx Nice posts

yusuf

07/09/09 02:18 am

Thank you very nice article on fluid and technical means

Çiçek Sepeti Blog

07/09/09 02:56 am

Thank you very nice article on fluid and technical means…

toplu konut

07/09/09 06:42 pm

Thannmks:)

mailing list broker

07/10/09 04:05 am

Find Lists is a mailing list broker offering high quality business mailing lists, consumer mailing lists, direct marketing lists, medical mailing lists, email lists. We are a mailing list company helping clients purchase lists. http://www.findlists.com

Amateur Porn

07/12/09 05:10 pm

thankss buddy its nice post

viagens baratas

07/12/09 05:30 pm

Great info

electric cigarette

07/12/09 06:16 pm

Brett, when do you plan to publish the part 3? Can’t wait though..really..

zha

07/12/09 08:32 pm

i hate blackberrys <a > learn yoga at home </a>

Commenting is not available in this section entry.

Blog.

Recent Entries

Making your (Facebook Dev) life easier.

I know from experience that using the Facebook API can be an exercise in confusion. That’s why I created this easy to use PHP Facebook Utility class.

Android for iPhone Developers - Part 2

Dive into the world of Android user interface creation.

Android for iPhone Developers - Part 1

Familiar with iPhone application development? Want get your learn on with Android? Then this article is for you.

New articles in the Lab!

The first 2 parts in a series on Android development from an iPhone developer’s perspective.

Lifting Anchor and Unfurling the Sails

I am embarking on a new adventure in life: sailing the seas of freelance.

PostMaster 2.1.0 is ready for download!

Finally! It’s been a little while, but I finally found a few slices of time to finish the latest iteration of PostMaster. Check out what’s new!

PostMaster 2.1.0 Recall

I’m recalling any 2.1.0 pre-release versions I have given out.

New site. New outlook.

Out with the old and in with the new!

PostMaster Info

Important info about the 2.1.0 release of the PostMaster WordPress plugin.

Code coming to the Lab

Helpful code snippets and hints for your programming pleasure.