Android 使用Intent在活动之间传递数据

直接上代码

第一个Activty:

public class MainActivity extends Activity {
    // 请求码,必须是唯一值
    private static final int TO_SECOND_ACTIVITY = 1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button gotoSecond = (Button) findViewById(R.id.button_1);
        gotoSecond.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                String data = "进入SecondActivity";
                intent.putExtra("extra_data", data);
                startActivityForResult(intent, TO_SECOND_ACTIVITY);
            }
        });
    }

    // 上面使用startActivityForResult()方法来启动SecondActivity
    // 则SecondActivity销毁后会回调onActivityResult()方法
    // 在这里得到返回的数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TO_SECOND_ACTIVITY) {
            switch (resultCode) {
            case RESULT_OK:
                String returnData = data.getStringExtra("data_return");
                Toast.makeText(this, returnData, Toast.LENGTH_LONG).show();
                break;
            default:
            }
        }
    }    
}

第二个Activity:

public class SecondActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.second_activity);
        
        // 获取传入的数据并显示
        Intent intent = getIntent();
        String data = intent.getStringExtra("extra_data");
        Toast.makeText(this, data, Toast.LENGTH_LONG).show();
        
        // 点击按钮返回上一个Activity
        Button finishThis = (Button) findViewById(R.id.button_finish_2);
        finishThis.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                returnDataAndClose();
            }
        });
    }
    
    // 返回数据并关闭当前活动
    private void returnDataAndClose(){
        Intent intent = new Intent();
        intent.putExtra("data_return", "学习安卓");
        setResult(RESULT_OK, intent);
        finish();
    }

    // 按下手机上的返回键时调用此活动
    @Override
    public void onBackPressed() {
        returnDataAndClose();
    }
    
    
}


你可能感兴趣的:(Android 使用Intent在活动之间传递数据)