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

Android Intent 傳值:Activity 之間參數傳遞完整流程

編輯:關於 Android 程式設計

Intent 除了負責啟動元件,也是 Activity 之間傳遞資料的標準做法。整個流程可以拆成四步:封裝資料、啟動目標、在目標端取出、必要時在 manifest 中註冊。

一、先理解幾個版面屬性

1)android:layout_width="match_parent":Google 把早期的 fill_parent 改名為 match_parent,語意更貼近實際行為——填滿父容器。「填滿」的意思就是有多少空間就佔多少空間。

2)android:layout_height="wrap_content":高度依內容調整,讓內部的文字與圖片完整呈現。布局元素會隨內容大小改變尺寸,大體等同於 Windows 控制項的 Autosize 屬性。

3)android:text:設定按鈕上顯示的文字。

二、在 MainActivity 中封裝並送出

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) this.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent(MainActivity.this, OtherActivity.class);
            intent.putExtra("name", "Deng");
            intent.putExtra("age", 23);
            startActivity(intent);
        }
    });
}

用明確指定目標元件類別的寫法啟動,這叫顯式 Intent。putExtra() 有多個重載版本,字串、整數、布林、以及實作 Parcelable 或 Serializable 的物件都能放。

三、建立 OtherActivity

版面配置 other.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">

    <TextView
        android:id="@+id/msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

OtherActivity.java:

public class OtherActivity extends Activity {
    private TextView textview;

    public OtherActivity() { }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);

        textview = (TextView) this.findViewById(R.id.msg);

        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        int age = intent.getIntExtra("age", 0);

        textview.setText("name" + name + ";" + "age" + age);
    }
}

記得覆寫 onCreate() 並設定 setContentView() 布局。取值的時候,字串型別沒有預設值參數,取不到會回傳 null;數值型別則必須給一個預設值,這裡 getIntExtra("age", 0) 的第二個參數就是取不到時的 fallback。

四、在 AndroidManifest.xml 註冊

自訂的 Activity 必須在 manifest 中宣告,否則啟動時會拋出 ActivityNotFoundException:

<activity android:name=".OtherActivity">
    <intent-filter>
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

補充:資料該放 Bundle 而非散在 Intent 裡

範例為了示範而直接呼叫 putExtra(),但實務上更推薦把相關資料包進一個 Bundle:

Bundle bundle = new Bundle();
bundle.putString("name", "Deng");
bundle.putInt("age", 23);
intent.putExtra("user_data", bundle);

接收端用 getBundleExtra("user_data") 取出。這樣做的好處是資料結構集中、擴充欄位時不必改動 Intent 的呼叫介面,也更容易整體替換或轉傳。

另外要留意大小限制。Intent 的資料是透過 Binder 傳遞的,而 Binder 緩衝區通常只有 1MB 左右,且是整個行程共用。塞入大張 Bitmap 是很多人遇到的 TransactionTooLargeException 元兇。若確實要傳圖片,應該傳 URI 或檔案路徑,讓接收端自行載入。

最後,若傳的是自訂物件,該類別需實作 Parcelable(效能較佳,Android 推薦)或 Serializable(Java 原生,寫法簡單但較慢)。

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