<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>
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>