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

startActivityForResult 完整教學:Activity 之間雙向傳值的標準做法

編輯:Android 開發實例

Activity 跳轉大家都知道用 startActivity(Intent)。但如果情境是:Activity1 跳到 Activity2,處理完之後還要把結果帶回 Activity1 呢?

有人會說,那在 Activity2 再 startActivity 一次不就得了?可以,但 startActivityForResult() 能更直接地完成這件事。

示例:Activity1 有兩個 EditText 用來接收使用者輸入的字串,要求把兩個字串串接起來。串接的工作交給 Activity2 做,做完再把結果回傳給 Activity1 顯示。

一、Activity1 的界面

<?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:id="@+id/first"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/second"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

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

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="...is waiting" />
</LinearLayout>

二、取得兩個輸入框的值

first  = (EditText) findViewById(R.id.first);
second = (EditText) findViewById(R.id.second);

三、打包並發送 Intent

Intent i = new Intent(this, Activity2.class);

Bundle b = new Bundle();
b.putString("first", first.getText().toString());
b.putString("second", second.getText().toString());

i.putExtras(b);

startActivityForResult(i, 10);

方法簽名值得細看:

public void startActivityForResult(Intent intent, int requestCode)

intent:系統依此決定要啟動哪個 Activity。
requestCode:這次請求的識別碼。回來時靠它判斷「這個結果是不是我當初要的那一個」——當一個 Activity 裡有多處 start 動機時尤其重要。

四、註冊點擊監聽

findViewById(R.id.start).setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        sendCalculate();
    }
});

五、Activity2 的界面

<?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" >

    <Button
        android:id="@+id/reply"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="reply" />
</LinearLayout>

六、Activity2 接收並處理

Intent i = this.getIntent();
Bundle b = i.getExtras();

String v1 = b.getString("first");
String v2 = b.getString("second");

value = v1 + v2;

注意這裡用的是 getIntent() 而不是 getCallingIntent()——兩者差別在於前者對任何啟動方式都有效,後者只在 forResult 情境下才有值。

七、把結果裝回去並關閉自己

Intent i = new Intent();
Bundle b = new Bundle();
b.putString("CALCULATION", value);
i.putExtras(b);

this.setResult(RESULT_OK, i);
this.finish();

setResult() 的第二個參數是回傳的 Intent;第一個參數是結果碼,常用值為 RESULT_OK、RESULT_CANCELED。若不呼叫 setResult,系統會預設回傳 RESULT_CANCELED,這是很多人「明明 finish 了卻收不到結果」的原因。

八、Activity1 接收並顯示

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (resultCode) {
        case RESULT_OK:
            Bundle b = data.getExtras();
            String string = b.getString("CALCULATION");
            updateText(string);
            break;
    }
}

實務上建議同時檢查 requestCode,避免多個請求的結果互相干擾:

if (requestCode == 10 && resultCode == RESULT_OK) {
    String result = data.getStringExtra("CALCULATION");
    updateText(result);
}

另外提醒:使用者若按返回鍵離開 Activity2,resultCode 會是 RESULT_CANCELED,而 data 可能為 null。取值前應先判空,否則容易 crashes。

九、現在更推薦寫法

上述是傳統做法。若你在新專案中實作類似需求,AndroidX 已提供 Activity Result API,不需要自己記 requestCode,也不用手動處理 onActivityResult:

private final ActivityResultLauncher<Intent> launcher =
        registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        String s = result.getData().getStringExtra("CALCULATION");
                        updateText(s);
                    }
                });

// 啟動
launcher.launch(new Intent(this, Activity2.class));

它天生就處理了設定變更與 requestCode 分派,也不會因為混淆而取錯結果。理解 startActivityForResult 的運作有助於除錯舊專案,但新程式碼請優先採用 Activity Result API。

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