Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

安卓基礎教學:從零建立並啟用你的第一個 Activity

編輯:Android 開發實例

跑完 HelloWorld、也大致看過專案結構之後,初學者接下來最想搞清楚的通常就是:Activity 到底怎麼建?其實流程只有四步,缺任何一步 Activity 都跑不起來。以下依序說明。

步驟一:建立一個繼承 Activity 的 Java 類

package com.androidwhy;

import android.app.Activity;

import android.os.Bundle;

public class HelloActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

}

}

步驟二:覆寫 onCreate 方法

如上所示,必須 Override onCreate()。這個方法是 Activity 被啟動時執行的第一個入口,角色有點像 Java 的 main(),初始化工作都放在這裡。記得第一行一定要先呼叫 super.onCreate(savedInstanceState),否則會直接拋出 SuperNotCalledException。

步驟三:準備對應的版面檔

程式碼中的 setContentView(R.layout.main) 指向 res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>

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

android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent">

<EditText android:layout_width="match_parent" android:id="@+id/editText1"

android:layout_height="wrap_content" android:hint="welcome to android.tgbus.com">

<requestFocus></requestFocus>

</EditText>

<LinearLayout android:layout_width="match_parent"

android:layout_height="wrap_content" android:id="@+id/linearLayout1">

<Button android:text="確定" android:id="@+id/okButton"

android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

<Button android:text="取消" android:id="@+id/cancleButton"

android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

</LinearLayout>

</LinearLayout>

這個版面用一個垂直的 LinearLayout 當外框,裡面放一個 EditText,再嵌一個水平 LinearLayout 裝兩顆按鈕(確定與取消)。<requestFocus> 的作用是讓輸入框在畫面出現時自動取得焦點、直接彈出鍵盤;若不希望一進來就彈鍵盤,把這段移除即可。

步驟四:在 AndroidManifest.xml 中註冊

完成前三步,你的 Activity 仍然無法使用,因為系統還不知道它的存在。必須到 AndroidManifest.xml 宣告:

<?xml version="1.0" encoding="utf-8"?>

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

package="com.androidwhy"

android:versionCode="1"

android:versionName="1.0">

<uses-sdk android:minSdkVersion="8" />

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".HelloActivity"

android:label="@string/app_name">

<intent-filter>

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

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

</intent-filter>

</activity>

</application>

</manifest>

這裡把 HelloActivity 設成了應用啟動時執行的 Activity。關鍵在 <intent-filter> 那兩行:action.MAIN 表示它是程式的進入點,category.LAUNCHER 表示它會出現在桌面啟動器中。一個 App 通常只有一個 Activity 帶這組組合,其餘 Activity 只需要 <activity> 標籤本身即可。

四步都完成後,執行專案就能看到畫面了。若日後新增的 Activity 忘了註冊,這是新手最常遇到的錯誤,記得回來檢查 Manifest。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved