首页 > 代码库 > Activity跳转&Bundle传递数据

Activity跳转&Bundle传递数据

Activity的跳转方式有两种:

1.startActivity(Intent intent),直接启动其他Activity

btnChange = (Button)findViewById(R.id.btnChange);
btnChange.setOnClickListener(new OnClickListener(){

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		Intent mIntent = new Intent();
		mIntent.setClass(MainActivity.this, AnotherActivity.class);
		startActivity(mIntent);
	}});

2.startActivityForResult(Intent intent,int requestCode),以指定的请求码启动Activity,并本程序在启动新Activity后会调用onActivityResult获取新的Activity传递回来的结果

2.1-Bundle:putExtras(Bundle data)/getExtras()、putExtra(String name,Xxx value)/getXxxExtra(String name)

I.MainActivity中的btn调用startActivityForResult:

btnChange = (Button)findViewById(R.id.btnChange);
btnChange.setOnClickListener(new OnClickListener(){

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		Intent mIntent = new Intent(MainActivity.this, AnotherActivity.class);
		startActivityForResult(mIntent,0);
	}});
II.MainActivity中重写onActivityResult监听返回的数据

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
	if(requestCode == 1 && resultCode == 1){
		Bundle data = http://www.mamicode.com/intent.getExtras();>III.在AnotherActivity中发送数据

btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
	@Override
	public void onClick(View v) {
		Intent intent = getIntent();
		intent.putExtra("Name", "John");
		//设置ResultCode
		AnotherActivity.this.setResult(0);
		AnotherActivity.this.finish();
	}
});




Activity跳转&Bundle传递数据