Intro/hello-android
From Android中文网
初步翻译了一下,如果出现错误不要笑话,请同志们共同改进吧。
目录 |
[编辑] Hello, Android!
First impressions matter, and 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, in Android, it's pretty easy. Here's how it looks:
第一印象,作为一个开发人员,我们对一个新的开发框架的第一印象通常是看他的”Hello,World!”程序有多简单。在Android中,实现起来是非常简单的。
实现Hello World需要几个步骤:
- Create the Project
- Construct the UI
- Run the Code: Hello, Android
- 创建项目
- 设计用户界面
- 运行程序:Hello,Android
The sections below spell it all out in detail.
以下几节讨论更加详细的内容
- Upgrading the UI to an XML Layout
- Debugging Your Project
- Creating a Project without Eclipse
- 通过(XML 布局)XML Layout更新用户界面
- 调试程序
- 不使用Eclipse创建项目
Let's jump in! 废话少说,马上开始。
Create the Project
[编辑] 创建项目
Creating the project is as simple as can be. An Eclipse plugin is available making Android development a snap. You'll need to have Eclipse 3.3 (Europa) or higher installed, and you'll need to install the Android Plugin for Eclipse. Once you have those installed, come back here.
创建项目非常简单,Eclipse的插件使Adroid的开发变得异常轻松。首先你需要安装一个3.3或以上版本的eclipse(译注:其实3.2也是可以的),然后给Eclipse安装一个Android插件。安装好上面的内容后,我们就可以开始了。
First, here's a high-level summary of how to build "Hello, World!":
首先,我们来一个总结来看看到底需要几步来完成我们的"Hello, World!"。
1. Create a new "Android Project" via the File > New > Project menu.
2. Fill out the project details in the New Android Project dialog.
3. Edit the auto-generated source code template to display some output.
1. 通过Eclipse的 File > New > Project 菜单创建"Android Project"项目。
2. 在新Android 项目对话框中添加项目的详细信息
3. 修改自动生成代码模板来显示一些东西
That's it! Next, let's go through each step above in detail. 上面3步已经足够了!接下来,让我们开始吧
1. Create a new Android Project
1. 创建Android项目 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".
在Eclipse中选择 File > New > Project 菜单项。如果你已经成功安装了Android 插件,你会在弹出的新项目对话框中看到一个叫做“Android”的条目,包含一个”Android Project”的项目
Once you've selected "Android Project", press the Next button.
选中"Android Project",点击 Next进行入下一步。
2. Fill out the project details
2. 填写项目的相关信息
The next screen allows you to enter the relevant details for your project. Here's an example:
这个窗口里你需要填写一些项目的相关信息.请看图中的示例:
Here's what each field on this screen means:
下面解释一下屏幕上的内容:
Project Name This is the name of the directory or folder on your computer that you want to contain the project.
这是计算机中保存项目文件目录的名称。
Package Name This is the package namespace — similar to the Java programming language — that you want all your source code to reside under. This also sets the package name under which the stub Activity will be generated.
这是和Java语言意义相同的包名(Package namespace)—你的源代码将属于这个包名。同时stub Activity也将据此生成。
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.google.android"; you should use a different one appropriate to your organization.
你所给出的报名必须保证在你的应用中是唯一的;因为这个原因,包的命名遵循域名方式(domain-style)就显得非常重要了;在实例中我们使用"com.google.android"作为包名;你可以选择一个适合你自己的包名。
Activity Name This is the name for the class stub that will be generated by the plugin. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to.
Android插件将根据这个名称来创建一个stub类。他是一个继承自Activity类的子类。Activity类似一个简单的可以运行和工作的类。它能够根据你的需要创建用户界面,当然了这不是必须的。
Application Name This is the human-readable title for your application. 这是你应用程序的标题。
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.
你可以通过选择"Use default location"这个复选框来项目文件的存储位置。
3.Edit the auto-generated source code
3.编辑自动生成的程序代码
After the plugin runs, you'll have a class named HelloAndroid that looks like this:
Android插件执行完毕后将创建一个叫做HelloAndroid类,他的内容如下:
public class HelloAndroid extends Activity { /** Called when the activity is first created. */ /**在activity被创建后执行*/
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
}
}
The next step is to start modifying it!
Construct the UI
[编辑] 创建用户界面
Once you've got the project set up, the obvious next step is to get some text up there on the screen. Here's the finished product — next we'll dissect it line by line:
创建好项目以后,我们要做的是在屏幕上显示一点文字。下面是完成后的代码,我们将逐行分析它:
public class HelloAndroid extends Activity { /** Called when the activity is first created. */ /**在activity被创建后执行*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
}
}
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.
在Android中,用户界面是由View来组成的。一个View就是一个drawable的对象,比如一个单选按钮,一个动画,或者(本例中)是一个文字标签。View子类型中用来显示文字 类是TextView。
Here's how you construct a TextView:
下面演示如何构建一个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.
TextView构造函数中的参数类型是Context。Context类可以简单的理解为系统的句柄;他提供访问了诸如资源、数据库以及程序设置的服务。Activity类继承自Context。我们的HelloAndroid类继承自Activity类,他同时也继承了Context。正因为如此我们才能使用’this’这个参数来创建TextView。
Once we've constructed the TextView, we need to tell it what to display:
上面我们已经创建了一个TextView,下面我们来让他显示些文字:
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:
我们已经创建了一个TextView并且告诉了他要显示什么,最后就是让他显示在屏幕上了,就像下面这样:
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.
setContentView()方法让系统知道哪个View是与Activity的界面有联系的。如果你的Activity没有执行这个方法,界面将什么都不会显示,系统只会显示空屏幕。我们的目的是要显示一些文字,所以我们在这个方法的参数中填上TextView。
There it is — "Hello, World" in Android! The next step, of course, is to see it running.
这就是我们Android中的"Hello, World"了!接下来当然是看看如何运行它了。
Run the Code: Hello, Android
[编辑] 运行程序:Hello, Android
The Eclipse plugin makes it very easy to run your applications. Begin by selecting the Run > Open Run Dialog menu entry; you should see a dialog like this:
Android提供的Eclipse插件使得运行我们的程序非常简单。选择Run > Open Run Dialog菜单;你会看到一个这样的对话框:
Next, highlight the "Android Application" entry, and then press 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".
接下来,选中"Android Application"这一项。点击左上角按钮(文档图标上有个加号的那个)或者简单双击"Android Application"项。你会得到一个叫做"New_configuration" 新launcher。
Change the name to something expressive, like "Hello, Android", and then pick your project by pressing 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.
选择一个更好的名字,比如"Hello, Android", 点击"Browse"按钮选择你的项目。(如果你现在打开了多个Android的项目,一定要确认你选择了正确的那个)。Android插件会自动的扫描你的项目来查找Activity 的子类,在"Activity:" 标签下面的下拉框中列出所有的选项。你的"Hello, Android" 只有一个,他将作为缺省的选项。
Press the "Apply" button. Here's an example: 点击 "Apply" 按钮。示例如下:
That's it — you're done! Press 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:
大功告成!点击run按钮,Androi模拟器将运行。当模拟器启动完成你将看到你的程序。到这里我们就完成了。
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.
这就是我们Android中 “Hello,World”。很简单吧,嗯?下面的章节我们会探讨一些比较深入的东西,对你学习Android肯定有所帮助。
Upgrading the UI to an XML Layout
[编辑] 通过XML Layout构造用户界面
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.
你刚刚完成"Hello, World"时通过编程来创建用户界面的。也就是说你在你的程序代码中来创建界面。如果你以前做过很多的界面编程,你一定知道有个非常麻烦的事情:在一大段代码中找到并且修改一个小的界面变化是很头疼的。而且也容易忘记属性与视图之间的关系,从而导致错误,浪费大量的时间来调试代码。
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:
这就是Android提供了一个替代创建用户界面的模式:基于XML的XML Layout文件。解释这个概念的最好方法就是创建一个例子。这个XML Layout文件实现了我们上面用程序代码实现的功能。
<?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 tags, where each tag is the name of a View class. In this example, it's a very simple tree of one element, a TextView. You can use the name of any class that extends View as a tag name 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 much simpler 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.
一般的Android XML Layout 文件 结构非常简单。它由树形的标记组成,每一个标记都是一个View类。在上面这个例子中只有一个元(element)-TextView。你可以在XML layout中使用任何一个继承自View的类,也包括你自己定义的类。这样简单的结构和语法使我们能够比使用代码更快的创建用户界面。它的灵感来自Web开发中用户界面与程序逻辑分开的模式。
In this example, there are also four XML attributes. Here's a summary of what they mean: 这个例子中只有4个XML属性,下面列出含义:
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.
TextView显示的文字内容,这个例子中显示 "Hello, Android"
So, that's what the XML layout looks like, but where do you put it? Under the res/ directory in your project. The "res" is short for "resources" and that directory contains all the non-code assets that your application requires. This includes things like images, localized strings, and XML layout files.
这就是XML layout的内容,但是该将它放在那里呢?在项目的res/ 目录中。这个"res"是对"resources"的缩写,这个目录中存放项目中所有不是代码的资源或文件。包括:图片,本地字符串,XML layout文件。
The Eclipse plugin creates one of these XML files for you. In our example above, we simply never used it. In the Package Explorer, expand the folder res/layout, and edit the file main.xml. Replace its contents with the text above and save your changes. Now open the file named R.java in your source code folder in the Package Explorer. You'll see that it now looks something like this:
Eclipse插件已经为我们创建了这些XML文件。在我们上面的例子中,我们根本没有使用过他们。在Package Explorer中展开res/layout,目录,修改其中的main.xml文件。使用上面的文本替换掉他的内容。现在从Package Explorer中的源代码文件夹中打开R.java文件,你将看到如下内容:
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.
项目中的R.java文件是对文件中所有定义资源的索引。可以用最简单的方式在代码中使用项目中定义的资源。利用Eclipse的代码提示功能可以更快找到需要的内容。
The important thing to notice for now is the inner class named "layout", and its member field "main". The Eclipse plugin noticed that you added a new XML layout file and then regenerated this R.java file. As you add other resources to your projects you'll see R.java change to keep up.
其中最重要的两个内部类就是"layou"和"main"。Eclipse插件会根据你在XML layout文件中更改自动生成R.java文件。当时你在项目中添加了其他资源后你会先R.java会马上发生变化。
The last thing you need to do is modify your HelloAndroid source code to use the new XML version of your UI, instead of the hard-coded version. Here's what your new class will look like. As you can see, the source code becomes much simpler:
最后一件事就是你要修改你的HelloAndroid 代码,让程序使用XML layout文件定义的界面而不是采用我们以前的硬编码方式。看看现在的代码,简单多了:
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
}
}
When you make this change, don't just copy-and-paste it in. Try out the code-completion feature on that R class. You'll probably find that it helps a lot.
不要简单的拷贝粘贴来修改文件,试试R类的代码自动完成,这是你或许感觉到R类的作用了。
Now that you've made this change, go ahead and re-run your application — all you need to do is press the green Run arrow icon, or select Run > Run Last Launched 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.
好,现在你已经完成了修改,让我们重新运行一下程序---你要做的就是点击以下有绿色箭头图标的Run按钮,或者选择Run>Run菜单来运行。你会看到和以前相同的结果。我们可以看出两种不同的布局方法结果是相同的。
There's a lot more to creating these XML layouts, but that's as far as we'll go here. Read the Implementing a User Interface documentation for more information on the power of this approach.
我们只是对XML layouts有了个大概的了解,你需要阅读用户界面部分的完整文档来获取进一步的信息。
Debugging Your Project
[编辑] 调试程序
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:
Android的Eclipse的插件也能够完美的与Eclipse的调试器集成。为了证实这一点,我们来做一个简单的测试。将你HelloAndroid 程序的代码改成这样:
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
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: 这段代码很明显将产生一个NullPointerException 异常。运行后你看到:
To find out what went wrong, set a breakpoint in your source code on the line "Object o = null;" (You can do this by double-clicking on the region to the left of the line number in Eclipse.) Then select Run > Debug Last Launched 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.
为了找出错误,我们在"Object o = null;"这一行设置一个断点(你可以通过双击eclipse编辑器行号左边的空余部分来创建)。选择 Run > Debug菜单进入到调试模式。你的程序在模拟器中重新启动,但是这次程序会在运行到断点的地方停住。就行你在其他开发工具中那样,你可以在Eclipse的Debug Perspective中检查代码。
Creating the Project without Eclipse
[编辑] 不使用eclipse创建项目
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.
如果你不使用Eclipse(比如其他IDE或者是使用简单的文本编辑器和命令行工具),那么Android的Eclipse插件就帮不了你了。但是别太担心--你不会因为不使用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.
Android 插件实际上只是对SDK里面的工具做了一下封装。因此可以使用其他工具来封装这些工具,比如'ant'来编译文件。(像emulator, aapt, adb, ddms这些工具都可以在文档中找到使用的方法)
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.
Android SDK 同时包含了一个名称为"activityCreator.py"的Python的程序脚本,用来创建项目中的代码和目录,以及一个兼容'ant'的build.xml文件。这使得你可以通过命令行或者使之与其他的IDE工具集成。
For example, to create a HelloAndroid project similar to the one we just created via Eclipse, you'd use this command:
例如,创建一个想刚才我们在eclipse中创建的HelloAndroid 项目,你可以使用这样的命令:
activityCreator.py --out HelloAndroid com.google.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.
为了编译这个项目,你必须使用ant命令。当命令成功完成后,你可以在'bin'目录中找到一个HelloAndroid.apk文件。这个.apt文件就是一个Android 包,你可以使用'adb'工具把它安装到模拟器中。
For more information on how to use these tools, please read the documentation cited above.
你可以在其他文档中找到这些工具更详细的用法和说明。
