Hello World程序運行分析

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>
這段代碼表示對HelloWorldActivity這個活動進行註冊,沒有在AndroidManifest.xml裏註冊的活動是不能使用的。其中intent-filter裏的兩行代碼非常重要,紅色字體表示HelloWorldActivity是這個項目的主活動,在手機上點擊應用圖標,首先啓動的就是這個活動。
其中,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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章