Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Activity 跳轉入門:用 Intent 打開第二個畫面

編輯:關於 Android 程式設計

開發環境:Android 4.1.1

幾乎所有 App 的第一個功能需求都是「換頁」。在 Android 裡,這件事由 Intent 負責,而它同時也是理解整個專案目錄結構的好起點。

功能描述

第一個 Activity(HelloworldActivity)顯示一段文字與一顆名為 Next 的按鈕。按下 Next 後進入第二個 Activity(NextActivity),畫面上只有一顆 Close 按鈕。

至於「關閉程式」這件事,網路上流傳的做法其實都不太可靠——Android 本身有返回鍵與最近使用清單等機制來管理生命週期,硬要終結自己反而容易出問題。所以這裡的 Close 按鈕先不做實際行為,留一個佔位。

跳轉的原理

關鍵只有一句:不要直接 new 另一個 Activity,而是丟一個 Intent 給系統,讓系統幫你開。

做法是在 Next 按鈕上掛一個 OnClickListener,一旦偵測到點擊,就用 intent.setClass() 指定目標,再呼叫 startActivity()。這樣寫的好處是元件之間彼此不認識,耦合度低,也符合系統統一管理生命週期的前提。

先搞清楚專案裡各目錄的分工

跳頁只是表象,真正該記住的是這些:

每個 Activity 都對應一個 XML 佈局檔,負責控制控制項的位置與屬性。
assets 與 res 都可以存放檔案,但 res 底下的資源會在 gen 目錄的 R.java 中自動產生對應的全域 id。
res/values/strings.xml 裡的每一筆字串,以及 res/layout 下的每個佈局檔,同樣都會在 R 類別裡取得一個 id。
AndroidManifest.xml 是整個應用的設定檔,Activity 都必須在此註冊,否則系統找不到它。
android.jar 是所有 Android 類別的來源。
View 是所有控制項的父類別。
Activity 可以理解為人機互動的畫面,也可以視為一個控制項的容器。

幾個 Eclipse 常用快捷鍵順手記一下:Ctrl+Shift+C 切換單行註解(//),Ctrl+Shift+/ 與 Ctrl+Shift+\ 切換區塊註解(/* */),Alt+/ 呼叫單字與方法補全,Ctrl+Shift+O 自動補上缺少的 import。

還有兩個 XML 與 Java 的差異要留意:setText() 裡不能寫資源引用(該寫 @string/xxx 的地方是 XML),資源顯示文字應該在 XML 中指定;XML 的註解格式是 <!-- 內容 -->,不能出現在屬性值或標記內部;而且 XML 語句結束不需要分號。

HelloworldActivity.java

package com.example.helloworld;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;               // 注意 view 的大小寫
import android.view.View.OnClickListener;
import android.widget.Button;

public class HelloworldActivity extends Activity {

    private Button my_button = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_helloworld);

        my_button = (Button) findViewById(R.id.my_button);
        my_button.setText("Next");
        my_button.setOnClickListener(new MyButtonListener());
    }

    class MyButtonListener implements OnClickListener {
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setClass(HelloworldActivity.this, NextActivity.class);
            HelloworldActivity.this.startActivity(intent);
        }
    }

    /*
     * 若不覆寫 onCreateOptionsMenu,系統啟動時會直接進入本程式,
     * 而不必先經過主畫面。為了方便除錯,這裡先不做選單。
     */
}

NextActivity.java

package com.example.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class NextActivity extends Activity {

    private Button my_button2 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);

        my_button2 = (Button) findViewById(R.id.my_button2);
        // setText 裡不能寫資源引用,例如 "@string/close" 是無效的
        my_button2.setText("Close");
    }
}

activity_helloworld.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerHorizontal="true"
        android:text="@string/wuwei"
        tools:context=".HelloworldActivity" />

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

activity_next.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/my_button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

AndroidManifest.xml

新加的 Activity 一定要在這裡登記,同時只有掛上 MAIN/LAUNCHER 意圖篩選器的那一個,才會成為啟動圖示。

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.helloworld"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity
            android:name=".HelloworldActivity"
            android:label="@string/hello_world">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".NextActivity"
            android:label="@string/close">
        </activity>

    </application>
</manifest>

實驗小結

這次大致摸清了 Android 專案各目錄的職責,也把開發流程走過一輪。由於 Java 與 XML 語法都還不熟,學習速度難免偏慢;好在方向明確——先讓 Intent 跳頁跑通,再回頭補語言基礎。

作者:tornadomeet

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