Intent传递类对象
本文转自http://www.cnblogs.com/shaocm/archive/2013/01/08/2851248.html,在此感谢作者
Android中Intent传递类对象提供了两种方式
一种是通过实现Serializable接口传递对象,另一种是通过实现Parcelable接口传递对象。
被传递的对象必须实现上述2种接口中的一种才能通过Intent直接传递。
1 Bundle.putSerializable(Key,Object); //实现Serializable接口的对象 2 3 Bundle.putParcelable(Key, Object); //实现Parcelable接口的对象
以下以最常用的Serializable方式为例 :
假设由登录界面(Login)跳转到主界面(MainActivity)传递的对象为登录的用户信息 User类
首先创建一个序列化类:User
1 public class User implements Serializable { 2 private int id; 3 private String userName; 4 private String password; 5 6 public int getId() { 7 return id; 8 } 9 public void setId(int id) { 10 this.id = id; 11 } 12 public String getUserName() { 13 return userName; 14 } 15 public void setUserName(String userName) { 16 this.userName = userName; 17 } 18 public String getPassword() { 19 return password; 20 } 21 public void setPassword(String password) { 22 this.password = password; 23 } 24 25 26 27 }
1 Intent intent = new Intent(); 2 intent.setClass(Login.this, MainActivity.class); 3 4 Bundle bundle = new Bundle(); 5 bundle.putSerializable("user", user); 6 intent.putExtras(bundle); 7 8 this.startActivity(intent);
1 Intent intent = this.getIntent(); 2 user=(User)intent.getSerializableExtra("user");
以上实现了对象的传递
如果传递的是List<Object>,可以把list强转成Serializable类型,而且object类型也必须实现了Serializable接口
1 Intent.putExtras(key, (Serializable)list)
接收
1 (List<YourObject>)getIntent().getSerializable(key)
浙公网安备 33010602011771号