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

Activity 間傳遞基本數據類型:Intent 與 Bundle

編輯:關於 Android 程式設計

Activity 之間傳值最常見的方式是 Intent 攜帶 Bundle。本文用最基礎的字符串傳遞演示完整流程。

核心思路

Activity 跳轉通過顯式 Intent 完成,數據則用 putExtra() 掛在 Intent 上:

Intent intent = new Intent();
intent.setClass(MainActivity.this, OtherActivity.class);
intent.putExtra("姓名", "我是蘇蘇");
startActivity(intent);

可以把 Intent 的 extras 理解為一個鍵值集合:「姓名」是鍵,「我是蘇蘇」是值,一對一對應。

接收端

在目標 Activity 中通過 getIntent().getExtras() 拿到 Bundle,再按鍵取值:

Bundle bundle = getIntent().getExtras();
String name = bundle.getString("姓名");
Toast.makeText(OtherActivity.this, name, Toast.LENGTH_LONG).show();

其他基本類型同理,只是取值方法換一下:

int age = bundle.getInt("年齡");
double height = bundle.getDouble("身高");
boolean isVip = bundle.getBoolean("是否會員");

完整代碼

MainActivity:

public class MainActivity extends Activity {

    private Button button;

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

        button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, OtherActivity.class);
                intent.putExtra("姓名", "我是蘇蘇");
                startActivity(intent);
            }
        });
    }
}

OtherActivity:

public class OtherActivity extends Activity {

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

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String name = bundle.getString("姓名");
            Toast.makeText(OtherActivity.this, name, Toast.LENGTH_LONG).show();
        }
    }
}

記得在 AndroidManifest.xml 中註冊 OtherActivity:

<activity android:name="com.example.activity.OtherActivity" />

實踐要點

  • 用常量定義鍵名:把 "姓名" 抽成 public static final String KEY_NAME = "name",避免兩端字符串不一致導致的隱患。
  • 接收端判空:getExtras() 在沒有數據時返回 null,直接調用會空指針。
  • 數據大小有限制:Intent extras 走 Binder 傳輸,緩衝區約 1MB,不適合傳大圖或長列表。
  • 不能傳的都是什麼:Intent 只能裝基本類型、String、Parcelable、Serializable 及其數組。自定義對象需要先實現接口,或者改用靜態變量、全局容器、EventBus 等其他方案。
  • 返回數據:若需要目標頁回傳結果,改用 startActivityForResult 加 setResult。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved