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

Android startActivityForResult 完整指南:頁面跳轉回傳資料與頭像上傳實作

編輯:關於 Android 程式設計

Android 開發中有一類很典型的互動:跳到另一個畫面填點東西,完成後帶著資料回到原本的畫面。最常見的例子就是登入流程——在「我的」頁面點了需要權限的功能,跳去登入頁,登入成功後回來,畫面上就多出了使用者資訊。這個行為靠的就是 startActivityForResult。

效果展示

主畫面版面配置

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

    <Button
        android:id="@+id/btn_a"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginTop="20dip"
        android:text="啟動A界面並返回數據" />

    <Button
        android:id="@+id/btn_b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginTop="20dip"
        android:text="啟動B界面" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dip"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="登錄" />

        <Button
            android:id="@+id/btn_logout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="注銷" />
    </LinearLayout>

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="30dip"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="20dip" />
</LinearLayout>

主畫面 Java 程式碼

public void onClick(View v) {
    Intent intent;
    switch (v.getId()) {
        case R.id.btn_a:
            intent = new Intent(MainActivity.this, ActivityA.class);
            intent.putExtra("data", "傳遞給A的數據");
            startActivityForResult(intent, A);
            break;
        case R.id.btn_b:
            intent = new Intent(MainActivity.this, ActivityB.class);
            intent.putExtra("data", "傳遞給B的數據");
            startActivity(intent);
            break;
        case R.id.btn_login:
            intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("data", "傳遞給登錄界面的數據");
            startActivityForResult(intent, LOGIN);
            break;
        case R.id.btn_logout:
            btnLogin.setClickable(true);
            logout.setVisibility(View.GONE);
            btnLogin.setText("登錄");
            break;
        default:
            break;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case A:
                Bundle bundle = data.getExtras();
                String back = bundle.getString("back");
                Toast.makeText(getApplicationContext(), "A界面傳回來的數據為:::::::" + back, 0).show();
                content.setText("A界面傳回來的數據" + back);
                break;
            case LOGIN:
                Bundle loginBundle = data.getExtras();
                String username = loginBundle.getString("username");
                String passwrod = loginBundle.getString("password");
                content.setText("登錄界面傳回來的數據" + username + ":::::::" + passwrod);
                btnLogin.setText("已登錄");
                btnLogin.setClickable(false);
                logout.setVisibility(View.VISIBLE);
                Toast.makeText(getApplicationContext(), username + ":::::::" + passwrod, 0).show();
                break;
            default:
                break;
        }
    }
}

兩個關鍵環節

第一是啟動方式。需要結果回傳時必須用 startActivityForResult(intent, requestCode),兩個參數分別是帶資料的 Intent 與請求碼。請求碼的用途是「辨識是哪個頁面回來的」——同一個 Activity 裡可能同時存在多處 startActivityForResult,回來時就靠 requestCode 分辨。

第二是回呼方法 onActivityResult(int requestCode, int resultCode, Intent data),它在被啟動的 Activity 結束並回傳資料時被呼叫:

・requestCode:你在啟動時傳入的辨識碼
・resultCode:結果碼,等於 RESULT_OK 代表對方正常結束並帶回了結果
・data:Intent 型別的資料,用 data.getExtras() 取出 Bundle 後再逐一取值

透過不同的結果碼搭配不同的請求碼,就能針對各個來源做對應處理。

被呼叫方也必須「配合」才能回傳資料

並不是所有用 startActivityForResult 啟動的頁面都會回傳資料——被啟動的那一方也要做相應設定。

ActivityA 示範了最完整的寫法:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout ll = new LinearLayout(this);
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    ll.setLayoutParams(params);
    ll.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("我是A界面");
    ll.addView(tv);

    Button close = new Button(this);
    close.setText("關閉界面並返回");
    close.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("back", "我是A界面返回的數據");
            setResult(RESULT_OK, intent);
            finish();
        }
    });
    ll.addView(close);
    setContentView(ll);

    Toast.makeText(getApplicationContext(), getIntent().getExtras().getString("data"), 0).show();
}

重點在這兩行:setResult(RESULT_OK, intent) 之後緊接著 finish()。順序不能顛倒——必須在關閉之前設定結果,否則回傳的資料會是空的。第一個參數是結果碼,也就是對方 onActivityResult 裡的第二個參數,一般固定設為 RESULT_OK。

不需要回傳的情況

ActivityB 是用 startActivity 啟動的,因此不必處理回傳:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activityb);
    Button close = (Button) findViewById(R.id.btn_close);
    close.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    Toast.makeText(getApplicationContext(), getIntent().getExtras().getString("data"), 0).show();
}

登入頁的實作

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    etUsername = (EditText) findViewById(R.id.et_username);
    etPassword = (EditText) findViewById(R.id.et_password);
    Button login = (Button) findViewById(R.id.btn_login);

    login.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String password = etPassword.getText().toString().trim();
            String username = etUsername.getText().toString().trim();
            Toast.makeText(getApplicationContext(), "登錄成功,返回原來界面", 0).show();
            Intent intent = new Intent();
            intent.putExtra("username", username);
            intent.putExtra("password", password);
            setResult(RESULT_OK, intent);
            finish();
        }
    });
    Toast.makeText(getApplicationContext(), getIntent().getExtras().getString("data"), 0).show();
}

登入成功後把使用者名稱與密碼送回主頁面顯示,同時主頁面的登入鈕要設為不可點擊,改由注銷操作接管。

這個小 demo 一共示範了兩件事:啟動 Activity 並帶結果回傳,以及啟動 Activity 但不回傳(後者更常用也更簡單)。

進階應用:上傳頭像

startActivityForResult 另一個高頻場景是更換頭像。

點擊頭像後彈出選擇對話框,可選「查看頭像」、「手機相冊」、「手機拍照」,選完相冊或拍照後進入裁剪畫面,裁剪結果回填到 ImageView;若有後端,再順勢上傳。

public void onClick(View v) {
    CharSequence[] items = { "查看頭像", "手機相冊", "手機拍照" };
    new AlertDialog.Builder(MainActivity.this).setTitle("上傳照片")
        .setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (which == SELECT_PICTURE) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                } else if (which == SELECT_CAMERA) {
                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判斷存儲卡是否可用
                    if (hasSdcard()) {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
                    }
                    startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
                } else if (which == SELECT_SCAN) {
                    // TODO 查看頭像
                }
            }
        }).create().show();
}

相冊與拍照都是系統應用,所以 Intent 使用系統預先定義好的 action:拍照是 android.media.action.IMAGE_CAPTURE,相冊是 Intent.ACTION_PICK。這也是跨應用呼叫時的標準做法——不指定元件名稱,只宣告意圖,讓系統決定由誰來處理。

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {          // 圖庫
            if (data == null) return;
            Uri uri = data.getData();
            crop(uri);
        } else if (requestCode == PHOTO_REQUEST_CAMERA) {    // 拍照
            if (hasSdcard()) {
                file = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
                crop(Uri.fromFile(file));
            } else {
                Toast.makeText(this, "未找到存儲卡,無法存儲照片!", 0).show();
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {       // 裁剪
            try {
                bmp = data.getParcelableExtra("data");
                photo.setImageBitmap(bmp);
                File tempFile = BitmapUtils.saveBitmapFile(bmp, PHOTO_FILE_NAME);
                upload(tempFile);   // 上傳到服務器
                pd = new ProgressDialog(this);
                pd.setMessage("頭像正在上傳中請稍後");
                pd.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

這裡的三個請求碼分工清楚:相冊、拍照、裁剪各自獨立,回來之後各走各的分支。這正是 requestCode 設計的價值所在——如果只有一個 resultCode,就完全無法分辨資料是從相冊還是相機來的。

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