Activity活動介紹

1. 什麼是活動
    它是一種可以包含用戶界面的組件,主要用於和用戶進行交互。
2. 活動的基本用法
    新建活動:
        src下新建一個class:FirstActivity 繼承 Activity 如下:

public class FirstActivity extends Activity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        

         setContentView(R.layout.first_layout);

    }   

}

項目中的任何活動都應該重寫Activity的onCreate()方法。

創建和加載佈局文件

Android程序的設計講究邏輯和視圖分離,最好每一個活動都能對應一個佈局,佈局就是用來顯示界面內容的;

新建佈局文件:

res/layout目錄下新建Android XML File first_layout.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

    

<Button

        android:id="@+id/button_1"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Button 1"

        />


</LinearLayout>
android:id 是給當前元素定義一個唯一標識符
@+id/id_name:在XML元素中定義一個id
@id/id_name: 在XML中引用一個id
android:layout_width指定當前元素的寬度,這裏使用match_parent表示當前元素和父元素一樣寬。
android:layout_height指定了當前元素的高度,這裏使用wrap_content表示當前元素的高度只要能剛好包含裏面的內容就行。
android:text 指定元素中顯示的文字內容。
加載佈局文件

setContentView(R.layout.first_layout);

setContentView()方法來給當前的活動加載一個佈局,一般需要傳入一個佈局文件的id。前面提到過,只需要調用R.layout.first_layout就可以得到first_layout.xml佈局的id,然後將它傳入setContentView()即可。

注意:這裏的R指的是項目包下的R文件。Android SDK還會自動提供一個android包下的R文件。

在AndroidManifest文件中註冊

所有的活動必須在AndroidManifest.xml中進行註冊才能生效。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.activitytest"

    android:versionCode="1"

    android:versionName="1.0" >

    <uses-sdk

        android:minSdkVersion="14"

        android:targetSdkVersion="19" />

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name=".FirstActivity"

            android:label="This is FirstActivity" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>

活動的聲明必須放在<application>標籤中,通過<activity>標籤來對活動進行註冊。

android:name來指定具體註冊哪一個活動

.FirstActivity:表示com.example.activitytest.FirstActivity的縮寫; 由於最外層的<manifest>標籤中已經通過package屬性指定了程序的包名,因此註冊活動時這一部分可以省略。

android:label 指定活動中標題欄的內容,標題欄是顯示在活動最頂部的。給活動指定的label不僅會成爲標題欄中的內容,還會成爲啓動器中應用程序顯示的名字。

<intent-filter>主活動聲明

如果你的應用程序中沒有聲明任何一個活動作爲主活動,這個程序仍然是可以正常安裝的,只是你無法在啓動器中看到或者打開這個程序。這種程序一般都是作爲第三方服務供其他的應用在內部進行調用的,如支付寶快捷支付服務。
至此已經可以創建並運行自己的活動了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章