建立一個android project,(我用的是2.3.3的Target),eclipse會自動產生以下內容——
——這是一個完整的可啟動並執行“hello world”程式。
運行結果為:
在螢幕上顯示出了Hello world,Demo_01Activity!
然後就開始分析以下這個程式吧——
在AndroidManifest.xml中有如下程式碼片段:
[html]
<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 的內容:
[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的內容:
[html]
<?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內容:
[html]
<?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中代碼所配置的:
[html]
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
其中表徵圖預設提供了三種解析度—— ,具體使用哪個由系統根據手機的不同解析度決定。
所以,由以上過程,在運行demo_01時會產生前面圖示的結果。——一個最簡單的hello world程式。
摘自 狼的第二個小窩