——這是一個完整的可運行的“hello world”程序。
運行結果爲:
在屏幕上顯示出了Hello world,Demo_01Activity!
-------------------------------------------------------------------------------------------
然後就開始分析以下這個程序吧——
在AndroidManifest.xml中有如下代碼段:
<activity
android:label="@string/app_name"
android:name=".Demo_01Activity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
即說明Demo_01Activity是程序的入口。
然後Demo_01Activity.java 的內容:
package barry.android.demo;
import android.app.Activity;
import android.os.Bundle;
public class Demo_01Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
所有的Activity都要繼承Activity類。
Demo01_Activity類覆寫了父類的onCreate方法,在程序啓動時會執行此方法。
在執行父類的onCreate方法之(第7行)後,執行了方法setContentView(R.layout.main),這個方法的作用是從佈局配置文件中加載內容到Activity中。
setContentView(R.layout.main)的參數——R.layout.main——R.java是自動生成的資源文件,我們用到的資源(res文件夾中的圖片、字符串、配置文件等)都會在R.java中自動生成相應的映射,引用資源時只需引用R文件中的相應映射即可。R.layout.main即對應res/layout/路徑下的main.xml。
main.xml的內容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
<LinearLayout>標籤指示控件的排列式爲線性,android:orientation="vertical"指示爲垂直排列,android:layout_width="fill_parent" 、android:layout_height="fill_parent" 指示顯示方式爲充滿父控件(Activity的父控件即整個屏幕)。
<LinearLayout>標籤內有一個<TextView>文本框標籤,指示顯示一個文本框,其三個屬性分別指示:文本框高度爲充滿父控件、寬度爲自動適應內容、以及顯示字符串 ”@String/hello” 。
@String/hello 指res/values/目錄下的string.xml的相應配置的名爲”hello”的字符串,值爲“Hello World, Demo_01Activity!”——
string.xml內容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Demo_01Activity!</string>
<string name="app_name">Demo_01</string>
</resources>
在手機程序菜單裏所顯示的圖標——,
以及程序的標題顯示——,也是由AndroidManifest.xml中代碼所配置的:
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
其中圖標默認提供了三種分辨率——,具體使用哪個由系統根據手機的不同分辨率決定。
所以,由以上過程,在運行demo_01時會產生前面圖示的結果。——一個最簡單的hello world程序。
--------------------------------------------------------------