码迷,mamicode.com
首页 > 其他好文 > 详细

Activity跳转&Bundle传递数据

时间:2014-11-26 11:27:37      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:activity   bundle   intent   

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 = intent.getExtras();
		//result为AnotherActivity回传的key为Name的value
		String result = data.getString("Name");
	}
}
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传递数据

标签:activity   bundle   intent   

原文地址:http://blog.csdn.net/miaoyunzexiaobao/article/details/41511069

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!