简单传值
FirstActivity.java
findViewById(R.id.button).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(FirstActivity.this, SecondActivity.class); intent.putExtra("extra_data","data"); // 传字符串, 更多传值方法 startActivity(intent); } });
SecondActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // 获取Intent对象 Intent intent = getIntent(); // 根据key获取value String extra_data = intent.getStringExtra("extra_data"); // 获取一个没有的可以 结果 null String extra_data2 = intent.getStringExtra("extra_data2"); Log.i(TAG, "onCreate: " + extra_data + extra_data2); }
回传值:
修改FirstActivity.java
/** * 监听获取activity返回的数据 * @param requestCode 传入的请求码 * @param resultCode 处理结果码 * @param data intent数据 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 1: if (resultCode == RESULT_OK) { String resultData = data.getStringExtra("data_return"); Log.i(TAG, "onActivityResult: " + resultData); } break; default: } }
修改SecondActivity.java
button = (Button) findViewById(R.id.button2); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.putExtra("data_return", "hello FirstActivity"); // 给上一个活动返回数据 setResult(RESULT_OK, intent);// 回调(FirstActivity.java中)onActivityResult方法 finish(); } });