2025-05-17

新建一個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程序。

 

摘自  狼的第二個小窩
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *