page.title=Hello, World @jd:body
As a developer, you know that the first impression you get of a development framework is how easy it is to write "Hello, World." Well, on Android, it's pretty easy.
It's particularly easy if you're using Eclipse as your IDE, because we've provided a great plugin that handles your project creation and management to greatly speed up your development cycles. Get Eclipse and visit the ADT Plugin page to install it.
If you're not using Eclipse, that's okay. Familiarize yourself with Developing in Other IDEs. You can then come back here and ignore anything about Eclipse.
Note: In some cases, you might want to click the screenshots below to get a bigger view.
From Eclipse, select the File > New > Project menu item. If the Android Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain a single entry: "Android Project".
Once you've selected "Android Project", click Next.
The next screen allows you to enter the relevant details for your project:
Here's what each field on this screen means:
The package name you use in your application must be unique across all packages installed on the system; for this reason, it's very important to use a standard domain-style package for your applications. In the example above, we used the package domain "com.android"; you should use a different one appropriate to your organization.
The checkbox for toggling "Use default location" allows you to change the location on disk where the project's files will be generated and stored.
After the plugin runs, you'll have a class named HelloAndroid
(found in your package, HelloAndroid > src > com.android.hello). It should look like
this:
public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Now, you could run this right away, but let's go a little further, so we understand more about what's happening. So, the next step is to modify some code!
Take a look at this revised code, below, and make the same changes to your HelloAndroid.java file. We'll dissect it line by line:
package com.android.hello; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello, Android"); setContentView(tv); } }
Tip: If you forgot to import the TextView package, try this: press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclipse shortcut to organize imports—it identifies missing packages and adds them for you.
In Android, user interfaces are composed of hierarchies of classes called Views. A View is simply a drawable object, such as a radio button, an animation, or (in our case) a text label. The specific name for the View subclass that handles text is simply TextView.
Here's how you construct a TextView:
TextView tv = new TextView(this);
The argument to TextView's constructor is an Android Context instance. The
Context is simply a handle to the system; it provides services like
resolving resources, obtaining access to databases and preferences, and so
on. The Activity class inherits from Context. Since our
HelloAndroid class is a subclass of Activity, it is also a Context, and so we can
pass the this
reference to the TextView.
Once we've constructed the TextView, we need to tell it what to display:
tv.setText("Hello, Android");
Nothing too surprising there.
At this point, we've constructed a TextView and told it what text to display. The final step is to connect this TextView with the on-screen display, like so:
setContentView(tv);
The setContentView()
method on Activity indicates to the system which
View should be associated with the Activity's UI. If an Activity doesn't
call this method, no UI is present at all and the system will display a blank
screen. For our purposes, all we want is to display some text, so we pass it
the TextView we just created.
There it is — "Hello, World" in Android! The next step, of course, is to see it running.
The Eclipse plugin makes it very easy to run your applications. Begin by selecting the Run > Open Run Dialog menu entry (in Eclipse 3.4, it's Run > Run Configurations). You should see a dialog like this:
Next, highlight the "Android Application" entry, and then click the icon in the top left corner (the one depicting a sheet of paper with a plus sign in the corner) or simply double-click the "Android Application" entry. You should have a new launcher entry named "New_configuration".
Change the name to something expressive, like "Hello, Android", and then pick your project by clicking the Browse button. (If you have more than one Android project open in Eclipse, be sure to pick the right one.) The plugin will automatically scan your project for Activity subclasses, and add each one it finds to the drop-down list under the "Activity:" label. Since your "Hello, Android" project only has one, it will be the default, and you can simply continue.
Click the "Apply" button. Here's an example:
That's it — you're done! Click the Run button, and the Android Emulator should start. Once it's booted up your application will appear. When all is said and done, you should see something like this:
That's "Hello, World" in Android. Pretty straightforward, eh? The next sections of the tutorial offer more detailed information that you may find valuable as you learn more about Android.
The "Hello, World" example you just completed uses what we call "programmatic" UI layout. This means that you construct and build your application's UI directly in source code. If you've done much UI programming, you're probably familiar with how brittle that approach can sometimes be: small changes in layout can result in big source-code headaches. It's also very easy to forget to properly connect Views together, which can result in errors in your layout and wasted time debugging your code.
That's why Android provides an alternate UI construction model: XML-based layout files. The easiest way to explain this concept is to show an example. Here's an XML layout file that is identical in behavior to the programmatically-constructed example you just completed:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Hello, Android"/>
The general structure of an Android XML layout file is simple: it's a tree of XML elements, where each element is the name of a View class (this example, however, is just one element). You can use the name of any class that extends View as an element in your XML layouts, including custom View classes you define in your own code. This structure makes it very easy to quickly build up UIs, using a more simple structure and syntax than you would in source code. This model is inspired by the web development model, where you can separate the presentation of your application (its UI) from the application logic used to fetch and fill in data.
In this example, there's just one View element, the TextView
,
which has four XML attributes. Here's a summary of what they mean:
Attribute | Meaning |
---|---|
xmlns:android
|
This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute. |
android:layout_width
|
This attribute defines how much of the available width on the screen this View should consume. In this case, it's our only View so we want it to take up the entire screen, which is what a value of "fill_parent" means. |
android:layout_height
|
This is just like android:layout_width, except that it refers to available screen height. |
android:text
|
This sets the text that the TextView should contain. In this example, it's our usual "Hello, Android" message. |
This layout file belongs in the res/layout/
directory in your project. The "res" is
short for "resources" and that directory contains all the non-code assets that
your application requires. Resources also include things like images, localized
strings, and XML layout files.
When you want a different design for landscape, put your layout XML file
in res/layout-land/
. Android will automatically look here when the layout changes.
Without it the layout will just be stretched.
The Eclipse plugin creates one of these XML files for you (main.xml
). In our example
above, we just ignored it and created our layout programmatically. In the Eclipse Package Explorer, expand the
folder res/layout/, and open the file main.xml
(once opened, you might need to click
the "main.xml" tab at the bottom to see the XML source). Replace its contents with
the sample XML above and save your changes.
Now open and modify your HelloAndroid
class source code to read the
XML layout, instead of the hard-coded version. Edit the file to look like this:
package com.android.hello; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
When you make this change, type it by hand to try the code-completion feature on that R class. You'll probably find that it helps a lot.
The setContentView()
method we're now using expects a reference to a layout resource.
We pass it R.layout.main
, which is the reference to the layout/main.xml
once it's
compiled into our R class by the Eclipse plugin. (More about the R class in a moment.)
Now that you've made this change, go ahead and re-run your application — all you need to do is click the green Run arrow icon, or select Run > Run History > Hello, Android from the menu. You should see.... well, exactly the same thing you saw before! After all, the point was to show that the two different layout approaches produce identical results.
There's a lot more to creating these XML layouts, but that's as far as we'll go here. Read the User Interface documentation for more information on creating layouts.
Open the file named R.java in your source code folder in the Package Explorer. It should look something like this:
public final class R { public static final class attr { }; public static final class drawable { public static final int icon=0x7f020000; }; public static final class layout { public static final int main=0x7f030000; }; public static final class string { public static final int app_name=0x7f040000; }; };
A project's R.java file is an index into all the resources defined in the file. You use this class in your source code as a sort of short-hand way to refer to resources you've included in your project. This is particularly powerful with the code-completion features of IDEs like Eclipse because it lets you quickly and interactively locate the specific reference you're looking for.
For now, notice the inner class named "layout", and its
member field "main". The Eclipse plugin noticed the XML
layout file named main.xml and generated a class for it here. As you add other
resources to your project (in the res/
directory), you'll see R.java change to keep up.
You should never edit this file by hand.
The Android Plugin for Eclipse also has excellent integration with the Eclipse debugger. To demonstrate this, let's introduce a bug into our code. Change your HelloAndroid source code to look like this:
package com.android.hello; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Object o = null; o.toString(); setContentView(R.layout.main); } }
This change simply introduces a NullPointerException into your code. If you run your application again, you'll eventually see this:
Press "Force Quit" to terminate the application and close the emulator window.
To find out more about the error, set a breakpoint in your source code
on the line Object o = null;
(double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello,
Android from the menu to enter debug mode. Your app will restart in the
emulator, but this time it will suspend when it reaches the breakpoint you
set. You can then step through the code in Eclipse's Debug Perspective,
just as you would for any other application.
If you don't use Eclipse (such as if you prefer another IDE, or simply use text editors and command line tools) then the Eclipse plugin can't help you. Don't worry though — you don't lose any functionality just because you don't use Eclipse.
The Android Plugin for Eclipse is really just a wrapper around a set of tools included with the Android SDK. (These tools, like the emulator, aapt, adb, ddms, and others are documented elsewhere.) Thus, it's possible to wrap those tools with another tool, such as an 'ant' build file.
The Android SDK includes a Python script named "activitycreator.py" that can be used to create all the source code and directory stubs for your project, as well as an ant-compatible build.xml file. This allows you to build your project from the command line, or integrate it with the IDE of your choice.
For example, to create a HelloAndroid project similar to the one we just created via Eclipse, you'd use this command:
activitycreator.py --out HelloAndroid com.android.hello.HelloAndroid
To build the project, you'd then run the command 'ant'. When that command successfully completes, you'll be left with a file named HelloAndroid.apk under the 'bin' directory. That .apk file is an Android Package, and can be installed and run in your emulator using the 'adb' tool.
For more information on how to use these tools, please read the documentation cited above.