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

Android 不同 Activity 之間的資料傳遞方式與 Intent 用法

編輯:關於 Android 開發

本文透過一個簡易的「人品計算器」小程式,實作從 A 畫面跳轉到 B 畫面並把資料帶過去的效果。

一、Intent 傳遞資料的兩大方式

從 A 介面打開 B 介面,把 A 的資料傳給 B,主要有兩種做法:

方式一:intent.setData(uri) / intent.getData()
適合傳遞簡單的 URI 型資料,例如 content://、https:// 之類的資源位址。

方式二:intent.putExtra(name, value)
最常用,可傳遞的型別很廣:

  • 八大基本型別及其陣列
  • String 與 CharSequence
  • 可序列化到檔案的物件:Serializable
  • 可序列化到記憶體的物件:Parcelable
  • Bitmap 等圖形物件
  • 多個值可打包進 Bundle(intent.putExtra("key", bundle))

實務上效能優先選 Parcelable,它在 Android 中的序列化速度明顯優於 Serializable。

本文來源:cnblogs.com/wuyudong

二、A 介面:activity_main.xml

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="人品計算器"
        android:textColor="#ff0000"
        android:textSize="26sp" />

    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入姓名" >
    </EditText>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:onClick="click"
            android:text="計算" >
        </Button>

    </RelativeLayout>

</LinearLayout>

介面如下:

三、B 介面:activity_result.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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="測試結果:"
        android:textColor="#ff0000"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="xxx:"
        android:textColor="#99000000"
        android:textSize="17sp" />

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100" />

</LinearLayout>

介面如下:

四、ResultActivity.java:接收並使用資料

package com.wuyudong.testrp;

import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ResultActivity extends Activity {

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

        TextView tv_result = (TextView) findViewById(R.id.tv_result);

        // 關鍵:用 getIntent() 取得呼叫方帶來的資料
        Intent intent = getIntent();
        String name = intent.getStringExtra("name");

        Random rm = new Random();
        int rp = rm.nextInt(101);

        tv_result.setText(name + ":您的人品值為:" + rp);

        ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
        pb.setProgress(rp);
    }
}

五、A 介面送出資料的寫法

在 MainActivity 中補上按鈕回呼,用 putExtra 放入資料後啟動目標 Activity:

public void click(View v) {
    EditText etName = (EditText) findViewById(R.id.et_name);
    String name = etName.getText().toString().trim();

    Intent intent = new Intent(this, ResultActivity.class);
    intent.putExtra("name", name);   // key 必須與接收端一致
    startActivity(intent);
}

六、實務補充

  • key 要集中管理:建議定義成 public static final String EXTRA_NAME = "name" 放在目標 Activity 中,避免字串打錯。
  • Intent 有大小限制:整個 Bundle 建議不超過 1MB,Process 間傳輸時更容易觸發 TransactionTooLargeException。傳大圖請改用 URI 或先存到檔案/Repository。
  • 回傳結果給上一頁:用 startActivityForResult() 搭配 setResult()(或新的 Activity Result API)。
  • 跨元件傳遞大量或複雜資料:與其塞進 Intent,不如放到共用 ViewModel、Repository 或單例狀態容器中。
  • 別忘了在 AndroidManifest.xml 註冊 ResultActivity,否則會拋出 ActivityNotFoundException。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved