码迷,mamicode.com
首页 > 移动开发 > 详细

Android学习笔记——Activity之间传递参数

时间:2016-03-30 01:23:05      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

Intent i = new Intent(CurrActivity.this, AnotherActivity.class);

i.putExtra("name", "这里可以传入各种常用数据类型,包括Bundle");
在AnotherActivity中可以通过
getIntent()方法获取CurrActivity传过来的Intent i
Intent i = getIntent();
String name = i.getStringExtra("name");//根据传入的数据类型来get不同的类型的Extra,这里传入的是字符串所以使用getStringExtra。
 
也可以通过传递Bundle来一次性传递多个数据
Intent i = new Intent(CurrActivity.this, AnotherActivity.class);
Bundle b = new Bundle();
b.putString("name", "CrazyBun");
b.putInt("age", 24);
传递Bundle的方式有两种:
i.putExtra("bundle", b);     //获取时使用i.getBundleExtra("bundle");
i.putExtras(b);     //获取时使用 i.getExtras();
然后在AnotherActivity中
//先getIntent()获取获取Intent
Intent i = getIntent();
//再从i中获取bundle
Bundle b = i.getExtras();
//之后从b中取数据即可
String name = b.getString("name");
String age = b.getInt("age");
//为了防止要获取的键值对不存在,可以在get()方法中增加一个参数,表示默认值,如:
String father = b.getString("father", "Bun");
这样的话,在传过来的Bundle中如果不存在father这个键值对的话,这里的father就会被赋值为Bun

Android学习笔记——Activity之间传递参数

标签:

原文地址:http://www.cnblogs.com/CrazyBun/p/5335382.html

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