AndroidManifest.xml中可以找到如下代码:
<activity
android:name="com.test.helloworld.HelloWorldActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
其中,HelloWorldActibity具体又有什么作用呢? 还记得之前说过,活动是Android应用程序的门面,凡是在应用中你看得到的东西,都是放在活动中的。打开HelloWorldActivity:
public class HelloWorldActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hello_world_layout);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hello_world, menu);
return true;
}
}
首先可以看到,HelloWorldActivity是继承自Activity的。Activity是Android系统提供的一个活动基类,我们项目中所有的活动都要继承它才能拥有活动的特性。然后可以看到一个onCreate()方法。这个方法是一个活动被创建时必定要执行的方法,其中只有两行代码,并没有Hello world! 的字样。
其实,Android程序的设计讲究逻辑和视图分离,因此是不推荐在活动直接编写界面的,更加通用的一种做法是,在布局文件中编写界面,然后在活动中引入进来。可以看到onCreate()方法的第二行调用了setContentView()方法,就是这个方法给当前的活动引入了一个hello_world_layout布局。
布局文件都是定义在res/layout目录下的,当你展开layout目录,找到hello_world_layout.xml,代码如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".HelloWorldActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
Hello world! 字符串也不是在布局文件中定义的。Android不推荐在程序中对字符串进行硬编码,更好的做法一般是把字符串定义在res/values/strings.xml里,然后可以再布局文件或代码中引用;
strings.xml
<resources>
<string name="app_name">Hello World</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>