这一篇我就从API Demos/Activity/Hello World开始吧。学习任何一个语言,我相信大家都是从hello world开始。
首先,我们用Eclipse打开API Demos工程,这里我只介绍android 2.2的sample code。选择File--->New--->Project...,在弹出的对话框种选择Android Sample Project,


public class HelloWorld extends Activity
{
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// See assets/res/any/layout/hello_world.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.hello_world);
}
}
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Demonstrates basic application screen.
See corresponding Java code com.android.sdk.app.HelloWorld.java. -->
<!-- This screen consists of a single text field that
displays our "Hello, World!" text. -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text"
android:layout_width="match_parent" android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:text="@string/hello_world"/>
也很简单,冒号里都是注释。整个布局里就放了个TextView控件。android:id="@+id/text"在资源R的id中给这个控件加个id叫text,以后在代码中可以通过这个id来获取这个控件。
android:layout_width="match_parent"设置控件的宽为填充父控件,这里就是整个屏幕的宽,match_parent等同于fill_parent,只是在android 2.2,即API8中改了名而已。
android:gravity="center_vertical|center_horizontal"设置控件内容垂直居中和水平居中,约束的是view中的内容,要区分android:layout_gravity,这是约束view这个控件整体在布局layout中的位置。
android:text="@string/hello_world"设置控件上的内容为values/strings.xml中hello_world的值<b>Hello,<i>World!</i></b>,<b/>加粗,<i/>倾斜.
这里没难点,layout相关属性,我们以后遇到layout再说。