简单数据传递
putExtra()
传递
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("data", "Hello SecondActivity");
startActivity(intent);
}
});
获取
使用 getStringExtra() 获取值
Intent intent = getIntent();
tv = (TextView) findViewById(R.id.text_tv);
tv.setText(intent.getStringExtra("data"));
传递数据包Bundle
选择传递Bundle类型
传递
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString("name", "Leo");
bundle.putInt("age", 15);
intent.putExtras(bundle);
startActivity(intent);
}
});
获取
Intent intent = getIntent();
Bundle data = intent.getExtras();
tv = (TextView) findViewById(R.id.text_tv);
tv.setText(String.format("name=%s, age=%d", data.getString("name"), data.getInt("age") ));