Intent_ex2

当SecondActivity需要回传参数时:
1. MainActivity启动SecondActivity时需要调用startActivityForResult()
并定义请求码
2. SecondActivity在合适的使用调用setResult()设置返回码和返回的参数
然后调用finish()结束当前Activity
3. MainActivity需要重写onActivityResult()捕获SecondActivity返回的结果

常用的返回码为:
RESULT_OK 成功
RESULT_CANCEL 失败
RESULT_FIRST_USER 用户自定义的返回码
RESULT_FIRST_USER + 1
RESULT_FIRST_USER + 2
……

MainActivity:

package com.example.day06_activity5;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

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

    public void btn_click(View view) {
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, SecondActivity.class);
        // 期待SecondActivity会传递参数回来
        startActivityForResult(intent, 8);
    }

    // 重写onActivityResult() 捕获SecondActivity返回的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 8 && resultCode == RESULT_OK) {
            String name = data.getStringExtra("name");
            int age = data.getIntExtra("age", 0);
            double weight = data.getDoubleExtra("weight", 0.0);
            Toast.makeText(MainActivity.this,
                    "姓名:" + name + ", 年龄:" + age + ", 体重:" + weight,
                    Toast.LENGTH_LONG).show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

SecondActivity:

package com.example.day06_activity5;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class SecondActivity extends Activity {

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

    public void btn_click_return(View view) {
        // 传递参数回去
        // 返回码有如下值:
        // RESULT_OK 成功
        // RESULT_CANCEL 失败
        // RESULT_FIRST_USER 用户自定义的返回码
        Intent data = new Intent();
        data.putExtra("name", "放远");
        data.putExtra("age", 58);
        data.putExtra("weight", 555.5);
        setResult(RESULT_OK, data);
        // 退出当前Activity
        finish();
    }
}
时间: 2024-10-12 20:08:37

Intent_ex2的相关文章