本篇摘自网址《通过 Intent 传递类对象》:http://www.cnblogs.com/shaocm/archive/2013/01/08/2851248.html
一、原文
Android中Intent传递类对象提供了两种方式一种是 通过实现Serializable接口传递对象,一种是通过实现Parcelable接口传递对象。
要求被传递的对象必须实现上述2种接口中的一种才能通过Intent直接传递。
Intent中传递这2种对象的方法:
- Bundle.putSerializable(Key,Object); //实现Serializable接口的对象
- Bundle.putParcelable(Key, Object); //实现Parcelable接口的对象
以下以最常用的Serializable方式为例 :
假设由登录界面(Login)跳转到主界面(MainActivity)传递的对象为登录的用户信息 User类
首先创建一个序列化类:User
- import java.io.Serializable;
- public class User implements Serializable {
- private int ID;
- private String UserName;
- private String PWD;
- public final void setID(int value)
- {
- ID = value;
- }
- public final int getID()
- {
- return ID;
- }
- public final void setUserName(String value)
- {
- UserName = value;
- }
- public final String getUserName()
- {
- return UserName;
- }
- public final void setPWD(String value)
- {
- PWD = value;
- }
- public final String getPWD()
- {
- return PWD;
- }
- }
登录窗体登录后传递内容
- Intent intent = new Intent();
- intent.setClass(Login.this, MainActivity.class);
- Bundle bundle = new Bundle();
- bundle.putSerializable("user", user);
- intent.putExtras(bundle);
- this.startActivity(intent);
接收端
- Intent intent = this.getIntent();
- user=(User)intent.getSerializableExtra("user");
以上就可以实现对象的传递。
补充:
如果传递的是List<Object>,可以把list强转成Serializable类型,而且object类型也必须实现了Serializable接口
- Intent.putExtra(key, (Serializable)list)
接收
- (List<YourObject>)getIntent().getSerializable(key)
二、附加
1、上面是通过将所有信息集成一个类,然后对这个类序列化来完成信息传递的,其实我们完全可以将每条信息逐个利用putExtras()逐个添加到里面,然后逐个取出。
如:
发送端:
- int postID=1;
- Intent intent=new Intent(getApplicationContext(), WriteStoryActivity.class);
- Bundle bundle = new Bundle();
- bundle.putSerializable("ACTION","PLUS");
- bundle.putSerializable("POSTID",postID);
- intent.putExtras(bundle);
- startActivityForResult(intent,REQUESTCODE );
接收端:
- Intent intent = this.getIntent();
- String action=(String)intent.getSerializableExtra("ACTION");
- String postID=(String)intent.getSerializableExtra("POSTID");
发现一个问题,在发送端发送的postID为int类型,而接收端不能将其强转成int类型,会报错,只能转成String类型。可见发送端发送与接收的类型是有限制的,现将目前所发现的接收后能强转的类型贴出来:
hashMap;
String;
2、除了上面方法以外,如果传送的信息全部是String类型,则可以用下面的方法;
发送端:
- Intent intent=new Intent(getApplicationContext(), WriteStoryActivity.class);
- Bundle bundle = new Bundle();
- bundle.putCharSequence("usr","harvic");
- bundle.putCharSequence("pwd","123456");
- bundle.putCharSequence("email","xxxxx@163.com");
- intent.putExtras(bundle);
- startActivity(intent);
- Intent intent = getIntent();
- Bundle bundle=intent.getExtras();
- String usr=bundle.getString("usr");
- String pwd=bundle.getString("pwd");
- String email=bundle.getString("email");
注意:如果通过Intent传递的数据量比较大(如不可控的List对象),就不要使用Intent传递,这样会造成Intent显示卡顿,对于大数据的Intent之间传递,建议使用EventBus通知机制。但这种方法只适用于,一个Activity在返回到其父Activity时的情况 。在新建Activity时,不要使用EventBus,因为这时Activity还没有被创建,使用EventBus去接的时候,根本接不到,而且还会报错。