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

Android Intent 傳值全攻略:頁面跳轉、putExtra 與 onActivityResult 回傳

編輯:關於 Android 程式設計

Intent(意圖)是 Android 的執行期綁定機制,用來在 Activity、Service、BroadcastReceiver 之間搭橋。你向系統描述「我想做什麼、要處理什麼資料」,系統再依描述找出合適的組件並把 Intent 交給它。這種中介設計讓呼叫方與被呼叫方彼此解耦,是 Android 元件化的基礎。

Intent 的兩個核心資訊

action 描述這次要做什麼動作;data 描述這個動作所作用的資料。明確指定目標元件時(如 new Intent(this, OtherActivity.class)),兩者可以省略;用於讓系統自行挑選元件時,才需要靠 action 與 data 比對 intent-filter。

形式一:跳轉並帶值過去

流程是:宣告 Intent 並指明來源與目的地 → 用 putExtra() 塞資料 → startActivity() 啟動。

public class MainActivity extends Activity {

    private TextView textView;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView1);
        btn = (Button) findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 建構式:Intent(來源, 目的地)
                Intent intent = new Intent(MainActivity.this, otherActivity.class);
                intent.putExtra("data", "當前是頁面2,信息來自頁面1");
                startActivity(intent);
                finish();   // 銷毀自己,避免 Activity 堆疊越堆越深
            }
        });
    }
}

接收端:

public class otherActivity extends Activity {

    private Button btn;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);
        textView = (TextView) findViewById(R.id.textView2);
        btn = (Button) findViewById(R.id.button2);

        // 取得啟動自己的 Intent,再依型別取出資料
        Intent intent = getIntent();
        String msg = intent.getStringExtra("data");
        textView.setText(msg);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(otherActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}

為什麼 startActivity() 之後要接 finish()?因為這個範例只在兩頁之間互相跳,每次跳轉都會產生新的 Activity。不銷毀舊的,返回鍵就會一路往回退、退不完。

別忘了在 Manifest 註冊新的 Activity,否則啟動時會直接拋 ActivityNotFoundException:

<activity android:name=".otherActivity" />

形式二:把結果帶回來

這才是實務上更常見的需求,差異有三:

  1. 用 startActivityForResult(intent, requestCode) 而非 startActivity()
  2. 回傳方用 setResult(resultCode, intent) 設定結果
  3. 來源方覆寫 onActivityResult() 接收,並比對 requestCode 與 resultCode

以下用「兩數相加」當例子:MainActivity 輸入兩個數字,跳到 otherActivity 輸入答案,按返回後把結果帶回主畫面。

// ---------- MainActivity ----------
public class MainActivity extends Activity {

    private EditText one, two, result;
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        one = (EditText) findViewById(R.id.one);
        two = (EditText) findViewById(R.id.two);
        result = (EditText) findViewById(R.id.result);
        btn = (Button) findViewById(R.id.btnGo);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int ione = Integer.parseInt(one.getText().toString());
                int itwo = Integer.parseInt(two.getText().toString());

                Intent intent = new Intent(MainActivity.this, otherActivity.class);
                intent.putExtra("one", ione);
                intent.putExtra("two", itwo);
                startActivityForResult(intent, 1);   // 請求碼
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 請求碼與結果碼都對上,才處理回傳的資料
        if (requestCode == 1 && resultCode == 2) {
            int three = data.getIntExtra("three", 0);
            result.setText(String.valueOf(three));
        }
    }
}
// ---------- otherActivity ----------
public class otherActivity extends Activity {

    TextView tvShow;
    EditText etResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other);
        tvShow = (TextView) findViewById(R.id.tvShow);
        etResult = (EditText) findViewById(R.id.etResult);

        Intent intent = getIntent();
        int a = intent.getIntExtra("one", 0);
        int b = intent.getIntExtra("two", 0);
        tvShow.setText(a + " + " + b + " = ?");

        Button btnResult = (Button) findViewById(R.id.btnReturn);
        btnResult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();          // 注意:不需要指定目的地
                int answer = Integer.parseInt(etResult.getText().toString());
                i.putExtra("three", answer);
                setResult(2, i);                  // 結果碼 + 資料
                finish();
            }
        });
    }
}

最容易被忽略的一點

回傳時建立的 Intent 不需要指定目標 Activity,因為它是被系統「送回」給呼叫方的,不是拿去啟動新畫面的。很多人會在這裡多寫一個 destination,結果引發非預期的跳轉。

另外,requestCode 與 resultCode 是兩個獨立概念:前者用來辨識「這個畫面上有哪幾個請求來源」,後者用來表達「這次回傳代表什麼結果」,慣例上用 RESULT_OK 與 RESULT_CANCELED。範例為求簡潔寫成 1 與 2,實作時請改用系統常數。

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